2016-12-13 35 views
1

我發誓我每天都在聽,對不起,如果我開始變得討厭,無論如何這裏有一些代碼示例:Bash - 如何使用if語句繼續執行程序,而不必重複代碼?

節目「問名」

if [ $0 -eq 0 ] || [ $0 -eq $1 ] 
then 
     if [ $# -eq 0 ] 
     then 
      echo "Sir I insist, I must know your name" 
      read $1 
     fi 
     #[the long code for if the number of arguments =1 goes here!!] 
     #the long code isn't important just imagine some fancy code here 
     #fancy code 
     #more fancy code 
fi 

基本上我只是希望它讓if語句之後,用戶能以某種方式修改參數的個數,然後繼續與腳本的其餘部分。

目前,用戶只需不斷輸入內容並永不停止,很可能是因爲'$ 1'作爲變量不起作用。

雖然我問這個問題的主要原因是要找出是否有辦法擺脫if語句並繼續使用該程序,即使輸入的參數符合特定條件。

什麼,我的意思是,如果你不明白我的另外一個例子:

#takes name as argument 
if [ $1 == "dave" ] 
then 
    echo "I don't like people called Dave, give me another name" 
    [SOMETHING HERE THAT MAKES $1 THIS INPUT, NOT SURE ABOUT 'read $1'] 
else 
    echo "Your name is cool, come inside!" 
fi 

的例子是有點不好,但是我基本上希望它使從回聲消息的用戶將能夠繼續使用代碼儘管被稱爲Dave。

一如既往,我欣賞任何建議。

[在標題中我提到DUPLICATE]

我基本上參照而不必重複所有其他代碼,並把它下的兩個不同的if語句。這是我目前唯一可以考慮的解決方案。

+0

可能是http://stackoverflow.com/questi的重複附件/ 41094178 /組合 - 兩慶典-while循環語句/ –

回答

1

看來你正在尋找set命令:

if [ $# -eq 0 ]; then 
    echo "Sir I insist, I must know your name" 
    read name 
    set -- "$name" 
fi 
if [ $# -eq 1 ]; then 
    # This is guaranteed to be true if $# was originally 0 
    # It won't be true if the user original provided 2 or more arguments. 
fi 

if [ "$1" = "dave" ] 
then 
    echo "I don't like people called Dave, give me another name" 
    read name 
    shift # discard the original first argument 
    set -- "$name" "[email protected]" 
else 
    echo "Your name is cool, come inside!" 
fi 
0

如果我正確理解你的問題,而不是IF語句,可能會更好地學習如何使用案例。情況的example

space=`df -h | awk '{print $5}' | grep % | grep -v Use | sort -n | tail -1 | cut -d "%" -f1 -` 

case $space in 
[1-6]*) 
    Message="All is quiet." 
    ;; 
[7-8]*) 
    Message="Start thinking about cleaning out some stuff. There's a partition that is $space % full." 
    ;; 
9[1-8]) 
    Message="Better hurry with that new disk... One partition is $space % full." 
    ;; 
99) 
    Message="I'm drowning here! There's a partition at $space %!" 
    ;; 
*) 
    Message="I seem to be running with an nonexistent amount of disk space..." 
    ;; 
esac 

如果我們把你的第二個示例工作:

case $1 in 
dave) 
    echo "I don't like people called Dave, give me another name" 
    ;; 
*) 
    echo "Your name is cool, come inside!" 
    ;; 
esac