2014-10-11 28 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