所以我有一个脚本,它从用户那里获取带有选项-y或-n的文件,并且需要-d脚本运行/example.sh-d文件-y或-n可变
file=""
如果用户没有在例如中传递文件,我需要进行验证
./example.sh -y --- it should give error "must provide file"`
./example.sh -n --- it should give error "must provide file"`
./example.sh -d --- it should give error "must provide file"
./example.sh -y -n --- it should give error "must provide file"
我想出了这个,但没用#检查文件是否提供
if [ $file -eq 1 ]; then
echo "No file provided"
exit 1
fi
# Does the file exist
which works for checking if the file exists but it only check if the file in there
if [[ ! -f $file ]]; then
echo
echo "Error: The file $file does not exist."
exit 1
fi
为什么不简单地循环参数并测试case
语句中的-d
、-n
和-y
选项呢。根据我的理解,文件名必须跟在-d
选项后面。在case
语句中处理-d
选项时,请检查下一个参数是否包含系统中存在的非空文件名,如果是,请设置文件名,例如filename="${argv[i+1]}"
。
当您退出选项处理循环时,只需测试是否设置了filename
,即可得到答案。
一个简短的例子可能是:
#!/bin/bash
argc=$# ## argument count
argv=("$@") ## array holding arguments (argument vector)
filename= ## filename is empty
## loop over all arguments, filename must follow -d
for ((i = 0; i < argc; i++)); do
case "${argv[i]}" in
## file exists and non-empty, set filename to argument
-d ) [ -s "${argv[i+1]}" ] && { filename="${argv[i+1]}"; };;
-n ) # do whatever for option n
;;
-y ) # do whatever for option y
;;
esac
done
[ -n "$filename" ] || { ## check filename set or exit
printf "error: file empty or not readable.n" >&2
exit 1
}
## valid filename received
printf "file '%s' found - script running.n" "$filename"
只有在-d
选项之后提供了有效的文件名,脚本才会运行。否则,它将给出一条错误消息并退出。
示例
$ ./process-opts.sh -y -n
error: file empty or not readable.
或
$ ./process-opts.sh -y -d -n
error: file empty or not readable.
最后
$ ./process-opts.sh -y -d README -n
file 'README' found - script running.
或按任何顺序:
$ ./process-opts.sh -y -n -d README
file 'README' found - script running.