getopt Unix 存储参数
Getopt Unix store parameters
我正在尝试将标志和变量都存储到脚本中。我将需要诸如用于 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
问题是 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 ]]
do
case "" in
-o)output=;shift;;
-s)sftpFlag=Y;;
--) break;;
esac
shift
done
echo "output file is: "$output
echo "SFTP flag is: "$sftpFlag
应该有预期的效果。
我正在尝试将标志和变量都存储到脚本中。我将需要诸如用于 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
问题是 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 ]]
do
case "" in
-o)output=;shift;;
-s)sftpFlag=Y;;
--) break;;
esac
shift
done
echo "output file is: "$output
echo "SFTP flag is: "$sftpFlag
应该有预期的效果。