Getopt Unix存储参数

Getopt Unix存储参数,unix,ksh,getopt,Unix,Ksh,Getopt,我试图将标志和变量存储到脚本中。我将需要像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;;

我试图将标志和变量存储到脚本中。我将需要像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

单个
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那样调用它,单个
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

问题在于
getopt-o:-i:-e:-s“$@”
将选项传递给getopt命令本身,其中一个选项
-s
需要一个参数(从手册页):

第二个问题是,您只是分配给一个变量,这意味着
$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

应该具有所需的效果。

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

第二个问题是,您只是分配给一个变量,这意味着
$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
应该有预期的效果