變量的作用域這是我的一個功能困惑中的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
變量的賦值?
如果你管入一個while循環,while循環將在一個子shell中。 – PSkocik
管道'|'導致while循環作爲並行進程執行,因此while循環結束時會丟失變量。你可以把它改成'while(condition);做...完成<<<「$ chmod_param」' – alvits