2015-10-15 53 views
1

變量的作用域這是我的一個功能困惑中的Bash

function safeChmod_ProcessOctalModes() { 
    local i=0 
    local targetpermission="" 
    local chmod_param=$1 
    # local folder_chmod_param=`echo $chmod_param | fold -w1` 
    # echo xxxxxxxxxxxx=$folder_chmod_param >/dev/tty 
    echo -n "$chmod_param" | \ 
    while read -n 1 ch; 
    do 
     if [ $i -eq 0 ] 
     then 
      i=$((i+1)) 
      continue 
     fi 
     i=$((i+1)) 

     if [ $ch -eq 0 ] 
     then 
      targetpermission=($targetpermission"---") 
      echo tp=$targetpermission >/dev/tty 
     elif [ $ch -eq 1 ] 
     then 
      targetpermission=($targetpermission"--x") 
      echo tp=$targetpermission >/dev/tty 
     elif [ $ch -eq 2 ] 
     then 
      targetpermission=($targetpermission"-w-") 
      echo tp=$targetpermission >/dev/tty 
     elif [ $ch -eq 3 ] 
     then 
      targetpermission=($targetpermission"-wx") 
      echo tp=$targetpermission >/dev/tty 
     elif [ $ch -eq 4 ] 
     then 
      targetpermission=($targetpermission"r--") 
      echo tp=$targetpermission >/dev/tty 
     elif [ $ch -eq 5 ] 
     then 
      targetpermission=($targetpermission"r-x") 
      echo tp=$targetpermission >/dev/tty 
     elif [ $ch -eq 6 ] 
     then 
      targetpermission=($targetpermission"rw-") 
      echo tp=$targetpermission >/dev/tty 
     elif [ $ch -eq 7 ] 
     then 
      targetpermission=($targetpermission"rwx") 
      echo tp=$targetpermission >/dev/tty 
     fi 
    done 
    echo tp_in_func=$targetpermission >/dev/tty 
    echo $targetpermission 
    return 0; 
} 

直到我while循環內,targetpermission變量正確填充內部代碼。但是,一旦循環完成,targetpermission就沒有了。

這是輸出。

chmod_param=0700 
tp=rwx 
tp=rwx--- 
tp=rwx------ 
tp_in_func= 

這是怎麼發生的?如何在while循環外保留targetpermission變量的賦值?

+2

如果你管入一個while循環,while循環將在一個子shell中。 – PSkocik

+2

管道'|'導致while循環作爲並行進程執行,因此while循環結束時會丟失變量。你可以把它改成'while(condition);做...完成<<<「$ chmod_param」' – alvits

回答

2

變化:

echo -n "$chmod_param" | \ 
while read -n 1 ch; do 
    #... 
done 

while read -n 1 ch; do 
    #... 
done <<<"$chmod_param" 

或者更一般地:

while read -n 1 ch; do 
    #... 
done < <(echo -n "$chmod_param") 

防止子shell創造,管道聯接到一個while循環的結果之中。

1

我以前見過這樣的行爲,這是由於bash中的某些構造創建新的上下文。基本上任何創建另一個shell的東西,比如反引號操作符或者$()運算符都有自己的上下文。在你的情況下,我認爲它可能是回聲饋送的while循環。