2017-06-02 110 views
0

我想找出答案可能很簡單的問題:我想傳遞帶有whitespaces的引號字符串作爲函數的獨立參數。將引用作爲參數傳遞給函數

有數據如下文件(例如):

one 
two three 
four five six 
seven 

而且有腳本2個簡單的功能:

params_checker() 
{ 
    local first_row="$1" 
    local second_row="$2" 
    local third_row="$3" 

    echo "Expected args are:${first_row} ; ${second_row} ; ${third_row}" 
    echo "All args are:" 
    for arg in "[email protected]"; do 
     echo "${arg}" 
    done 
} 

read_from_file() 
{ 
    local args_string 

    while read line; do 
     args_string="${args_string} \"${line}\"" 
     echo "Read row: ${line}" 
    done < ./test_input 

    params_checker ${args_string} 
} 

read_from_file 

換句話說,我希望得到的文本行文件作爲參數功能params_checker(從文件中的每一行作爲不同的參數,我需要保留行中的空格)。試圖使聯合字符串引用 「子」 是失敗的,而產量爲:

~/test_sh$ sh test_process.sh 
Read row: one 
Read row: two three 
Read row: four five six 
Read row: seven 
Expected args are:"one" ; "two ; three" 
All args are: 
"one" 
"two 
three" 
"four 
five 
six" 
"seven" 

預期爲$ 1 = 「一個」,$ 2 = 「兩個三」,$ 3 = 「四五六」 ... 在傳遞給params_checker期間引用$ {args_string}給出了另一個結果,字符串作爲單個參數傳遞。

你能幫忙找出正確的方法如何將文件中的空白字符串作爲不同的獨立函數聲明傳遞嗎?

非常感謝您的幫助!

回答

1

在bash/ksh/zsh中,你會使用一個數組。在sh中,可以使用參數「$ 1」,「$ 2」等:

read_from_file() 
{ 
    set --     # Clear parameters 

    while read line; do 
     set -- "[email protected]" "$line" # Append to the parameters 
     echo "Read row: ${line}" 
    done < ./test_input 

    params_checker "[email protected]"  # Pass all parameters 
} 
0

你去那裏,這應該給你你在找什麼:

#!/bin/bash 
params_checker() 
{ 
    local first_row="$1" 
    local second_row="$2" 
    local third_row="$3" 
    local forth_row="$4" 

    echo "Expected args are: ${first_row} ; ${second_row} ; ${third_row} ; ${forth_row}" 

    echo "All args are:" 
    for i in "[email protected]" 
    do 
     echo "$i" 
    done 
} 

read_from_file() 
{ 
    ARRAY=() 
    while read line; do 
     echo "Read row: ${line}" 
     ARRAY+=("$line") 
    done < ./test_input 

    params_checker "${ARRAY[@]}" 
} 

read_from_file; 

這應該在BASH正常工作。如果你的文件名爲test.sh,你可以像這樣運行./test.sh

+0

將此變量分配給自己的目的是什麼? –

+0

謝謝@chepner。這更乾淨。 –

相關問題