2012-12-06 107 views
1

可能重複:
Using getopts in bash shell script to get long and short command line options如何在shell腳本中編寫用戶定義的選項?

這是我寫

#! /bin/bash 

getopts master $1 

while getopts ":master" opt; do 
    case $opt in 
    master) 
     echo "-master was triggered! $1 was entered" >&2 
     ;; 
    \?) 
     echo "Invalid option: -$OPTARG" >&2 
     ;; 
    esac 
done 

的代碼,這是輸出我是getting-

]$ ./test123.sh -master 123 
./test123.sh: line 3: getopts: `-master': not a valid identifier 

我如何定義用戶定義的選項?

回答

3

我認爲有幾個問題。

  1. 我不明白這是什麼(getopts master $1)在做什麼,你可以刪除它
  2. 我想你需要單個字符參數(即-m VS -master)

例如下面似乎工作:

#!/bin/bash 
while getopts ":m" opt; do 
    case $opt in 
    m) 
     echo "-m was triggered! $1 was entered" >&2 
     ;; 
    \?) 
     echo "Invalid option: -$OPTARG" >&2 
     ;; 
    esac 
done 
+0

當我運行腳本我得到的輸出是'-m被觸發! -m被輸入了,但是我希望輸出是'-m被觸發了! 123進入了' – AlwaysALearner

+0

明白了。我必須把它寫成'echo'-m被觸發!$ 2被輸入「>&2」 – AlwaysALearner