2013-01-25 45 views
8

我不知道是否有可能,但我想編寫像常規可執行文件一樣使用選項的shell腳本。作爲一個非常簡單的例子,考慮被配置爲執行shell腳本foo.sh:如何使用選項編寫Unix shell腳本?

./foo.sh 
    ./foo.sh -o 

和代碼foo.sh作品像

#!/bin/sh 
    if ## option -o is turned on 
     ## do something 
    else 
     ## do something different 
    endif 

是否可能,如何做到這一點?謝謝。

回答

9
sgeorge-mn:stack sgeorge$ cat stack.sh 
#!/bin/sh 
if [[ $1 = "-o" ]]; then 
    echo "Option -o turned on" 
else 
    echo "You did not use option -o" 
fi 

sgeorge-mn:stack sgeorge$ bash stack.sh -o 
Option -o turned on 

sgeorge-mn:stack sgeorge$ bash stack.sh 
You did not use option -o 

FYI:

$1 = First positional parameter 
$2 = Second positional parameter 
.. = .. 
$n = n th positional parameter 

更多整齊/靈活的選擇,閱讀其他線程:Using getopts in bash shell script to get long and short command line options

+0

謝謝。其實我知道爭論的竅門,但那太蹩腳了...'getopt'看起來很酷。 – 4ae1e1

+0

該選項必須只有第一個參數?如果我有兩種選擇,你如何區分? –

2

這是怎樣的方式來做到這一點的一個腳本:

#!/usr/bin/sh 
# 
# Examlple of using options in scripts 
# 

if [ $# -eq 0 ] 
then 
     echo "Missing options!" 
     echo "(run $0 -h for help)" 
     echo "" 
     exit 0 
fi 

ECHO="false" 

while getopts "he" OPTION; do 
     case $OPTION in 

       e) 
         ECHO="true" 
         ;; 

       h) 
         echo "Usage:" 
         echo "args.sh -h " 
         echo "args.sh -e " 
         echo "" 
         echo " -e  to execute echo \"hello world\"" 
         echo " -h  help (this output)" 
         exit 0 
         ;; 

     esac 
done 

if [ $ECHO = "true" ] 
then 
     echo "Hello world"; 
fi 

點擊here

+0

這是真正的解決方案,因爲它允許h)選項中的任何選項以任何順序 –

+0

我想你應該用'$ 0'替換'args.sh' –