linux - 将引用作为参数传递给函数

标签 linux shell sh quoting

我想找到可能非常简单的问题的答案:我想将带空格的引号字符串作为函数的独立参数传递。

有如下数据文件(举例):

one
two three
four five six
seven

还有一个带有两个简单函数的脚本:

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

换句话说,我想从文本文件中获取行作为函数 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} 给出了另一个结果,字符串作为单个参数传递。

您能否帮助找出如何将此类带有空格的字符串作为不同的独立函数参数从文件中传递的正确方法?

非常感谢您的帮助!

最佳答案

在 bash/ksh/zsh 中你会使用一个数组。在 sh 中,您可以使用参数“$1”、“$2”等:

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
}

关于linux - 将引用作为参数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44335144/

相关文章:

Linux内存分段

linux - 为 Linux (Gnome) shell 脚本创建 UI 的工具

bash - 如何在bash中杀死后抑制终止消息?

eclipse - 如何在 Eclipse 中运行系统 shell/终端?

c++ - shell 如何管理子进程?

linux - 将每 X 行输入放入一个新列

linux - 将文件路由到 Linux 中的正确文件夹

docker - 如何让/etc/profile 在 Alpine/Docker 中自动运行

BASH 同时将大写字母转换为小写字母,反之亦然

linux - 检查文件是否存在 [SH]