【问题标题】:Getopt Unix store parametersGetopt Unix 存储参数
【发布时间】:2017-01-30 16:21:42
【问题描述】:

我正在尝试将标志和变量都存储到脚本中。对于 SFTP,我需要 -s 和输出文件的 -o 之类的东西。我正在尝试将这些存储到变量中以供以后使用。用法是 Script.ksh -o test.txt。输出应该是

output file is: test.txt
sftpFlag=Y

脚本内容如下,

args=`getopt -o:-i:-e:-s "$@"`

for arg in $args
do
    case "$arg" in
            o)output=$arg;;
            s)sftpFlag=Y
    esac
done

echo "output file is: "$output
echo "SFTP flag is: "$sftpFlag

【问题讨论】:

    标签: unix ksh getopt


    【解决方案1】:

    问题是getopt -o:-i:-e:-s "$@" 将选项传递给getopt 命令本身,而-s 选项之一需要一个参数(来自手册页):

    -s, --shell shell
     Set quoting conventions to those of shell.  If the -s option is not given,
     the BASH conventions are used.  Valid arguments are currently 'sh' 'bash',
     'csh', and 'tcsh'.
    

    第二个问题是您只是分配给一个变量,这意味着 $args 获取值 -o test.txt -s --(来自您的示例),它在一个循环中得到处理。

    所以重写你的代码:

    args=`getopt o:i:e:s "$@"`
    eval set -- "$args"
    while [[ -n $1 ]]
    do
        case "$1" in
                -o)output=$2;shift;;
                -s)sftpFlag=Y;;
                --) break;;
        esac
        shift
    done
    
    echo "output file is: "$output
    echo "SFTP flag is: "$sftpFlag
    

    应该有预期的效果。

    【讨论】:

      【解决方案2】:

      单个s 表示它是一个标志,而o: 表示它接受一个参数。 $OPTARG 会给你真正的论据。

      #!/bin/bash
      
      while getopts ":so:" opt; do
        case $opt in
          o)
            output=$OPTARG
            ;;
          s) sftpFlag=Y 
             ;;
          \?)
            echo "Invalid option: -$OPTARG" >&2
            ;;
        esac
      done
      
      echo "output file is: "$output
      echo "SFTP flag is: "$sftpFlag
      

      你可以这样称呼它$ test.sh -s -o output.txt

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-11-05
        • 2013-02-26
        • 1970-01-01
        • 1970-01-01
        • 2015-09-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多