Search code examples
linuxshellshquoting

Passing quoted as arguments to the function


I would like to find out answer on probably quite simple question: I would like to pass quoted strings with whitespaces inside as a standalone arguments for function.

There is the following file with data (for example):

one
two three
four five six
seven

And there is script with 2 simple functions:

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 "$@"; 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

In other words I would like to get rows from text file as arguments to function params_checker (each row from file as different parameter, I need to keep whitespaces in the rows). Attempt to make combined string with quoted "substrings" was failed, and output was:

~/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"

Expectation is $1="one", $2="two three", $3="four five six" ... Quoting of ${args_string} during passing to params_checker gave another result, string is passed as a single argument.

Could you please help to find out correct way how to pass such strings with whitespaces from file as a different standalone function argumets?

Thanks a lot for help!


Solution

  • In bash/ksh/zsh you'd use an array. In sh, you can use the parameters "$1", "$2" etc:

    read_from_file()
    {
        set --                   # Clear parameters
    
        while read line; do
            set -- "$@" "$line"  # Append to the parameters
            echo "Read row: ${line}"
        done < ./test_input
    
        params_checker "$@"      # Pass all parameters
    }