一举测试多个文件条件(BASH)? [英] Test multiple file conditions in one swoop (BASH)?
问题描述
在为 bash shell 编写代码时,通常需要测试文件(或目录)是否存在(或不存在)并采取适当的措施.这些测试中最常见的是...
Often when writing for the bash shell, one needs to test if a file (or Directory) exists (or doesn't exist) and take appropriate action. Most common amongst these test are...
-e
- 文件存在,-f
- 文件是一个普通文件(不是目录或设备文件),-s
-文件不是零大小,-d
- 文件是一个目录,-r
- 文件有读权限,-w
- 文件有写,或 -x
执行权限(针对运行测试的用户)
-e
- file exists, -f
- file is a regular file (not a directory or device file), -s
- file is not zero size, -d
- file is a directory, -r
- file has read permission, -w
- file has write, or -x
execute permission (for the user running the test)
正如在此用户可写目录中所示,这很容易确认....
This is easily confirmed as demonstrated on this user-writable directory....
#/bin/bash
if [ -f "/Library/Application Support" ]; then
echo 'YES SIR -f is fine'
else echo 'no -f for you'
fi
if [ -w "/Library/Application Support" ]; then
echo 'YES SIR -w is fine'
else echo 'no -w for you'
fi
if [ -d "/Library/Application Support" ]; then
echo 'YES SIR -d is fine'
else echo 'no -d for you'
fi
➝ 没有 -f 给你 ✓
➝ 是的 SIR -w 很好 ✓
➝ 是的 SIR -d 很好 ✓
我的问题,虽然看起来很明显,也不太可能是不可能的 - 是如何简单地组合这些测试,而不必为每个条件单独执行它们......不幸的是......
My question, although seemingly obvious, and unlikely to be impossible - is how to simply combine these tests, without having to perform them separately for each condition... Unfortunately...
if [ -wd "/Library/Application Support" ]
▶ -wd: unary operator expected
if [ -w | -d "/Library/Application Support" ]
▶ [: missing `]'
▶ -d: command not found
if [ -w [ -d "/Library.... ]] & if [ -w && -d "/Library.... ]
▶ [: missing `]'
➝ 没有 -wd 给你 ✖
➝ 没有 -w |-d 给你 ✖
➝ 没有 [ -w [ -d .. ]] 给你 ✖
➝ 没有 -w &&-d 给你 ✖
我在这里错过了什么?
推荐答案
您可以对多个条件使用逻辑运算符,例如-a
用于 AND
:
You can use logical operators to multiple conditions, e.g. -a
for AND
:
MYFILE=/tmp/data.bin
if [ -f "$MYFILE" -a -r "$MYFILE" -a -w "$MYFILE" ]; then
#do stuff
fi
unset MYFILE
这篇关于一举测试多个文件条件(BASH)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!