传递文本文件作为参数/变量[bash]



我试图传递一个文本文件作为一个特定的参数,并打印其名称和内容…

#!/bin/bash
## set input args
while getopts "f" option; do
case "${option}" in
f)
arg3=${OPTARG};;  
esac
done
## script
echo $arg3
echo $(cat $arg3)

(用于运行它:sh myscript.sh -f filelist)

真的有问题,因为连文件名都没有出现!(奇怪的是,在bash中一切都很顺利,为什么呢?)

根据@Barmar的回答(谢谢!)我忘了f的冒号了…但是,由于我试图使这个参数是可选的,所以这个应该放在后面。基于这另一个问题和@Barmar的观点,"最后"代码可以是这样的:

#!/bin/bash
## set input args
while getopts ":f" option; do
case "${option}" in
f)
# Check next positional parameter
eval nextopt=${$OPTIND}
# existing or starting with dash?
if [[ -n $nextopt && $nextopt != -* ]] ; then
OPTIND=$((OPTIND + 1))
arg3=$nextopt
else
echo "Not filelist specified, closing..." && exit
fi
;;
esac
done
## script
echo $arg3
echo $(cat $arg3)

最新更新