[英]bash: How do I identify the filename argument among arguments passed from the command line?
我知道我是否有命令./run -c -p '$' -s 10 file.txt
我可以这样写bash脚本
while read line; do
# ...
done < $6
但是,如果该命令可能具有或不具有一个/某些选项,该怎么办?
./run -p '$' -s 10 file.txt
或这个
./run '$' -s 10 file.txt
那如何在脚本中获取文件名?
如果文件名始终位于参数列表的末尾,则可以使用"${@: -1}"
选择最后一个参数。 摘自: https : //stackoverflow.com/a/1854031/3565972
例如。:
while read line; do
...
done < "${@: -1}"
使用getopts
处理选项(也允许它们以任意顺序使用):
#!/usr/bin/env bash
while getopts cp:s: option; do
case $option in
c)
echo "-c used"
;;
p)
echo "-p used with argument $OPTARG"
;;
s)
echo "-s used with argument $OPTARG"
;;
*)
echo "unknown option used"
exit 1
;;
esac
done
shift $(( OPTIND - 1 ));
echo "Arguments left after options processing: $@"
现在,如果运行此命令:
$ ./test.sh -c -p '$' -s 10 file.txt
-c used
-p used with argument $
-s used with argument 10
Arguments left after options processing: file.txt
如果要在脚本./run中获取文件名。 然后,您可以使用$#来获取参数的总数。 因此,您可以编写如下:
eval filename=\$$#
如果只想从这样的行中获取文件名:./run ** ** ** ** file.txt
您可以如下使用awk:
line="./run ** ** ** ** file.txt"
echo $line | awk '{print $NF}'
祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.