sh shell脚本可选参数未被读取

时间:2014-10-11 10:12:38

标签: shell sh

在我的shell脚本中,我正在读取两个可选参数。 第一个参数没有被读取。以下是代码:

#! /bin/sh  
while getopts "f:c:" opt;  
do  
case "${opt}" in  
f) file=${OPTARG}   
echo "" "File Name: ${file}"  
;;  
c) str=${OPTARG}  
echo "" "String: ${str}"  
;;  
esac    
done  

当我运行我的脚本时:

$ sh myscript.sh -f filename.txt -c someString 

输出:

$ File Name:  
$ String: someString

请告诉我哪里出错了。 我已尝试过getopts中的所有选项:

:f:c  
f:c  
f:c:  
:f:c:  

1 个答案:

答案 0 :(得分:1)

由于拼写错误,您的代码无效     c) str=${OPTAGR}
echo "" "String: ${str}"
;;
在上面你有str=${OPTAGR}的拼写错误它应该是str=${OPTARG} 我已执行下面的代码,它工作正常     #! /bin/sh while getopts "f:c:" opt; do case "${opt}" in f) file=${OPTARG} echo "" "File Name: ${file}" ;; c) str=${OPTARG} echo "" "String: ${str}" ;; esac done 产量    ajay@Ajay:~$ ./new.sh -f filename.txt -c sometext File Name: filename.txt String: sometext