测试多个文件条件一举(BASH)? [英] Test multiple file conditions in one swoop (BASH)?

查看:230
本文介绍了测试多个文件条件一举(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你✓结果
➝YES SIR -w是罚款✓结果
➝YES 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你✖

我缺少的是在这里吗?

What am I missing here?

推荐答案

您可以使用逻辑运算符将多个条件,例如 -a

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆