解析 bash 脚本中的参数/选项/标志
我正在尝试解析 bash 脚本中的选项。如何使用 getopts 来查看是否已输入可选标志。
FILE1=$1
FILE2=$2
outputfile=''
while getopts "o" OPTION
do
case $OPTION in
o)
outputfile=$OPTARG
;;
esac
done
if [ ! $outputfile -eq '' ]
then
cat $FILE1 | paste - | $FILE1 - | tr "\t" "\n" | paste $FILE1 $FILE2 | tr '\t' '\n' > $outputfile
else
cat $FILE1 | paste - | $FILE1 - | tr "\t" "\n"
paste $FILE1 $FILE2 | tr '\t' '\n'
fi
I am trying to parse an option in a bash script. how can I use getopts to see whether an optional flag has been entered.
FILE1=$1
FILE2=$2
outputfile=''
while getopts "o" OPTION
do
case $OPTION in
o)
outputfile=$OPTARG
;;
esac
done
if [ ! $outputfile -eq '' ]
then
cat $FILE1 | paste - | $FILE1 - | tr "\t" "\n" | paste $FILE1 $FILE2 | tr '\t' '\n' > $outputfile
else
cat $FILE1 | paste - | $FILE1 - | tr "\t" "\n"
paste $FILE1 $FILE2 | tr '\t' '\n'
fi
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里存在很多问题。您需要首先解析选项(getopts循环),然后从参数列表中删除它们(使用
shift $(($OPTIND-1))
),然后获取FILE1和 FILE2 来自 $1 和 $2。其次,您需要告诉 getopts -o 接受一个参数(getopts "o:"
)。第三,您的 getopts 循环应包括检查无效选项(并且您可能还应确保指定了 FILE1 和 FILE2)。第四,在检查 $outputfile 是否为空时,需要用双引号括起来,然后使用字符串测试(-eq 检查数字是否相等,如果使用它来比较数字以外的任何内容,则会给出错误)。第五,文件名应该用双引号引起来,以防其中有任何有趣的字符。最后,您尝试执行的实际命令(paste、tr 等)没有意义(所以我几乎不理会它们)。这是我重写的机会:There are a number of problems here. You need to parse options (the getopts loop) first, then remove them from the argument list (with
shift $(($OPTIND-1))
), then get FILE1 and FILE2 from $1 and $2. Second, you need to tell getopts that -o takes an argument (getopts "o:"
). Third, your getopts loop should include checking for an invalid option (and you should probably also make sure both FILE1 and FILE2 were specified). Fourth, when checking whether $outputfile is blank, you need double-quotes around it and then use a string test (-eq checks for numeric equality, and will give an error if you use it to compare anything other than numbers). Fifth, you should have double-quotes around the filenames in case they have any funny characters in them. Finally, the actual commands you're trying to execute (paste, tr, etc) don't make sense (so I pretty much left them alone). Here's my shot at a rewrite: