MLS*_*LSC 2 bash if-statement exit
这是我的脚本的一部分:
#!/bin/bash
USAGE(){
echo "Usage: ./`basename $0` <File1> <File2>"
}
if [ "$#" -ne "2" ]; then
USAGE
exit 1
fi
if [ ! -f "$1" ]; then
echo "The file \"$1\" does not exist!"
exit 1
fi
if [ ! -f "$2" ]; then
echo "The file \"$2\" does not exist!"
exit 1
fi
Run Code Online (Sandbox Code Playgroud)
我想检查file1是否不存在打印:
The file "file1" does not exist!
Run Code Online (Sandbox Code Playgroud)
如果file2不存在打印:
The file "file2" does not exist!
Run Code Online (Sandbox Code Playgroud)
如果两者都不存在打印:
The files "file1" and "file2" don't exist!
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
我想知道最合乎逻辑的(STANDARD)方法是什么。
你当然可以这样做...... 有很多方法可以获得这个。最简单的也许是:
if [ ! -f "$1" ] && [ ! -f "$2" ]; then
echo "The files \"$1\" and \"$2\" do not exist!"
exit 1
else
if [ ! -f "$1" ]; then
echo "The file \"$1\" does not exist!"
exit 1
fi
if [ ! -f "$2" ]; then
echo "The file \"$2\" does not exist!"
exit 1
fi
fi
Run Code Online (Sandbox Code Playgroud)
如果你不想做两次检查,你可以使用变量;像这样:
if [ ! -f "$1" ]; then
NOT1=1
fi
if [ ! -f "$1" ]; then
NOT2=1
fi
if [ -n "$NOT1" ] && [ -n "$NOT2" ]
....
Run Code Online (Sandbox Code Playgroud)