下面是做這件事:
fun(){
read -r "$1"
declare -n var="$1" #use a nameref -- see `help declare`
var=${var//[\' ]/} #clean the contents with string substitution
}
fun testingvar <<<"/path/file"; echo "$testingvar"
fun testingvar <<<"'/path/file'"; echo "$testingvar"
fun testingvar <<<" /path/ file'"; echo "$testingvar"
此輸出:
/path/file
/path/file
/path/file
即,所有的投入得到了清理,並投入經$1
傳遞其命名變量。
Namerefs:
基本上,namerefs像自動取消引用指針,除了它們指向的變量,而不是地址。它們既可以用作l值也可以用作r值,並且它們在創建後始終是自動引用的。
您可以使用namerefs要解決的事實,你不能分配給變量變量,即你不能做的:
foo=bar
然後
$foo=42 #illegal
到分配42至bar
,但你可以做:
declare -n foo=bar
foo=42 #now bar is 42
編輯: 如果希望只在開頭和結尾刪除所有單引號和空格,但是,你可以使用extglob
:
fun(){
local settings="$(shopt -p extglob)" #save extglob settings
shopt -s extglob #set extglob
read -r "$1"
declare -n var="$1" #use a nameref -- see `help declare`
var=${var##+([ \'])}; var=${var%%+([ \'])}
eval "$settings" #restore extglob settings
}
fun testingvar <<<"/path/file"; echo "$testingvar"
fun testingvar <<<"'/path/file'"; echo "$testingvar"
fun testingvar <<<" /pa'th/ f'ile'"; echo "$testingvar"
編輯2 - nameref少用EVAL版本:
fun(){
local settings="$(shopt -p extglob)" #save extglob settings
shopt -s extglob #set extglob
local var
read -r var; var=${var##+([ \'])}; var=${var%%+([ \'])}
eval "$1=\$var" #avoids interpolating the var value for eval to avoid code injections via stdin
eval "$settings" #restore extglob settings
}
fun testingvar <<<"/path/file"; echo "$testingvar"
fun testingvar <<<"'/path/file'"; echo "$testingvar"
fun testingvar <<<" /pa'th/ f'ile'"; echo "$testingvar"
[殼牌參數擴展(https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion)和'$ {!名}'可能是什麼你在追求。請注意,在'read'中,通常你會指定沒有'$'的名字(例如'read -r value'),因爲你想讀入變量,而不是讀入它的當前值。 –
'test'對於shell函數來說是一個可怕的名字......'test'已經是大多數現代shell中的內置shell。 – twalberg
是的,你是對的。但在我的真實劇本中,它有另一個名字。謝謝你的提示。 – OscarAkaElvis