Answers:
#!/bin/sh
if [ "$#" -ne 1 ] || ! [ -d "$1" ]; then
echo "Usage: $0 DIRECTORY" >&2
exit 1
fi
转换:如果参数数目(从数字上)不等于1,或者第一个参数不是目录,则将用法输出到stderr并以失败状态代码退出。
更友好的错误报告:
#!/bin/sh
if [ "$#" -ne 1 ]; then
echo "Usage: $0 DIRECTORY" >&2
exit 1
fi
if ! [ -e "$1" ]; then
echo "$1 not found" >&2
exit 1
fi
if ! [ -d "$1" ]; then
echo "$1 not a directory" >&2
exit 1
fi
if [ "$#" -ne 1 ] ; then
或者if ! [ -d "$1" ]; then
查看引起问题的子句。
-d
。如果您想添加单独的支票,则可以-e
用来检查是否存在。
-e
如果文件存在,则返回true。我在答案中添加了更友好的错误报告。
猫script.sh
var1=$1
var2=$2
if [ "$#" -eq 2 ]
then
if [ -d $var1 ]
then
echo directory ${var1} exist
else
echo Directory ${var1} Does not exists
fi
if [ -d $var2 ]
then
echo directory ${var2} exist
else
echo Directory ${var2} Does not exists
fi
else
echo "Arguments are not equals to 2"
exit 1
fi
如下执行它-
./script.sh directory1 directory2
输出将像-
directory1 exit
directory2 Does not exists
shell
意思是/bin/sh