2014-10-11 56 views
0

在我的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: 
+0

海峡= $ {} OPTAGR应海峡= {} OPTARG哦 – Jdamian 2014-10-11 10:39:33

+0

我似乎有误此处键入它..:P码具有海峡= $ {} OPTARG – aiman 2014-10-11 10:43:37

+0

谢谢Jdamian:D ..typo错误杀了我:P – aiman 2014-10-11 10:46:55

回答

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 输出 [email protected]:~$ ./new.sh -f filename.txt -c sometext File Name: filename.txt String: sometext