bash 检查输入是否不包含文件
bash check if input doesn't contain a file
我想编写一个脚本,当用户输入包含的参数不是文件时显示错误消息。
例如:
./script.sh test.pdf test1.pdf test2.pdf
应该可以正常工作。
但是:
./script.sh test.pdf test1.pdf notAfile
应该显示一条错误消息。
脚本应该容忍 [-b int] 选项,您可以将其放在文件之前。
例如
./script.sh -b 5 test.pdf test1.pdf test2.pdf
应该运行也可以
对于命令行参数解析,检查getopt。示例:
args=($(getopt -u '-o b:' -- $@))
files=false
for i in "${args[@]}"; do
$files && [ ! -f "$i" ] && echo "File not found: $i"
if [ "$i" == '--' ]; then files=true; fi
done
-b
参数让它有点棘手。这是一种可移植的方法:
b_seen=
b=
for arg; do
if test "$b_seen"; then
b="$arg"
b_seen=
elif test "$arg" = -b; then
b_seen=yes
elif test ! -f "$arg"; then
echo error: not a file: $arg
fi
done
有一个限制:如果有多个-b,最后一个会覆盖前面的
我想编写一个脚本,当用户输入包含的参数不是文件时显示错误消息。
例如:
./script.sh test.pdf test1.pdf test2.pdf
应该可以正常工作。
但是:
./script.sh test.pdf test1.pdf notAfile
应该显示一条错误消息。
脚本应该容忍 [-b int] 选项,您可以将其放在文件之前。
例如
./script.sh -b 5 test.pdf test1.pdf test2.pdf
应该运行也可以
对于命令行参数解析,检查getopt。示例:
args=($(getopt -u '-o b:' -- $@))
files=false
for i in "${args[@]}"; do
$files && [ ! -f "$i" ] && echo "File not found: $i"
if [ "$i" == '--' ]; then files=true; fi
done
-b
参数让它有点棘手。这是一种可移植的方法:
b_seen=
b=
for arg; do
if test "$b_seen"; then
b="$arg"
b_seen=
elif test "$arg" = -b; then
b_seen=yes
elif test ! -f "$arg"; then
echo error: not a file: $arg
fi
done
有一个限制:如果有多个-b,最后一个会覆盖前面的