在bash脚本中解析参数/选项/标志

时间:2011-11-17 22:02:51

标签: linux bash getopt

我正在尝试解析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

1 个答案:

答案 0 :(得分:6)

这里有很多问题。您需要首先解析选项(getopts循环),然后从参数列表中删除它们(使用shift $(($OPTIND-1))),然后从$ 1和$ 2获取FILE1和FILE2。其次,你需要告诉getopts -o接受一个参数(getopts "o:")。第三,你的getopts循环应该包括检查一个无效的选项(你应该也确保指定了FILE1和FILE2)。第四,当检查$ outputfile是否为空时,你需要在它周围使用双引号然后使用字符串测试(-eq检查数字相等,如果你使用它来比较数字以外的任何东西,将会出错)。第五,你应该在文件名周围加上双引号,以防它们中有任何有趣的字符。最后,您尝试执行的实际命令(粘贴,tr等)没有意义(所以我几乎不管它们)。这是我重写的镜头:

#!/bin/sh
outputfile=''
while getopts "o:" OPTION
do
    case $OPTION in
    o)
        outputfile="$OPTARG"
    ;;
    [?])
        echo "Usage: $0 [-o outfile] file1 file2" >&2
        exit 1
    ;;
    esac
done
shift $(($OPTIND-1))

if [ $# -ne 2 ]; then
    echo "Usage: $0 [-o outfile] file1 file2" >&2
    exit 1
fi
FILE1="$1"
FILE2="$2"

if [ -n "$outputfile" ]; 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
相关问题