2016-06-07 76 views
4

我想創建一個名爲傳遞給該函數的參數的var。有可能嗎?然後過濾它的內容,以便在讀取數據前後刪除可能的空格和單引號。不工作示例:Bash。使用參數名稱創建var並清除它的值

function test() { 
    read $1 
    [[ ${1} =~ ^\'?(.*)(\'.*)?$ ]] && 1="${BASH_REMATCH[1]}" 
} 

test "testingvar" 
#At this point, the user sent some data to the read statement 
echo $testingvar 

對於在read語句中收到的數據,我們可以收到一些不同的字符串。讓我們來看看這3個例子:

/path/file 
'/path/file' 
/path/file' <-notice a space after the quote 

在所有例子中,正則表達式必須清理並讓/無可能引號和空格路徑/文件....和我說,都在一個稱爲的帕拉姆VAR功能。是夢還是可以在bash中完成?提前致謝。

+0

[殼牌參數擴展(https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion)和'$ {!名}'可能是什麼你在追求。請注意,在'read'中,通常你會指定沒有'$'的名字(例如'read -r value'),因爲你想讀入變量,而不是讀入它的當前值。 –

+0

'test'對於shell函數來說是一個可怕的名字......'test'已經是大多數現代shell中的內置shell。 – twalberg

+0

是的,你是對的。但在我的真實劇本中,它有另一個名字。謝謝你的提示。 – OscarAkaElvis

回答

2

下面是做這件事:

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" 
+0

非常好!但替代對我來說是無效的。它清除了空格......我只需要在數據前後清理空格。該路徑可能包含空格,不應刪除。 – OscarAkaElvis

+0

@OscarAkaElvis我編輯了答案。 – PSkocik

+1

可以注意到,namerefs('declare -n')僅在'bash' 4.3+中可用。 –

相關問題