gpt4 book ai didi

bash - 将字符串传递给带有空格的 bash 函数

转载 作者:行者123 更新时间:2023-12-02 04:33:09 24 4
gpt4 key购买 nike

我从文件中读取了一行

line="1 \"Some Text Here\""

以及一个带有两个参数的函数

print() {
echo $1
echo $2
}

当我执行时

print $line

我得到的输出是

1
"Some

我想要得到的是

1
Some Text Here

最佳答案

如果您信任输入,可以使用eval (通常要避免,因为恶意输入字符串可能会做不需要的事情):

line="1 \"Some Text Here\""
eval print "$line" # `print` is the shell function from the question

即使使用无害的输入字符串,eval如果输入字符串包含所谓的 shell 元字符,命令将中断:| & ; ( ) < > .

此外,如果字符串恰好包含诸如 * 之类的标记看起来像路径名模式(glob),它们会无意中被扩展;相关的模式字符是:* ? [ ] .

因此,为了使上述内容更加稳健,使用 \ 对输入字符串中的转义模式字符和元字符进行转义。 如下:

eval print "$(sed 's/[][*?&;()<>]/\\&/g' <<<"$line")"

更新:事实证明,不需要 eval ,毕竟:问题可以通过 xargs 解决,它识别字符串文字中带引号的子字符串。:

#!/usr/bin/env bash

# Sample function that prints each argument passed to it separately
print() {
for arg; do
echo "[$arg]" # enclose value in [] to better see its boundaries
done
}

# Sample input string with embedded quoted strings, an unqoted
# glob-like string, and an string containing shell metacharacters
line="1 \"double-quoted string\" * 'single-quoted string' string-with-;|>-(metachars)"

# Let `xargs` split the string into lines (-n 1) and read the
# result into a bash array (read -ra).
# This relies on `xargs`' ability to recognize quoted strings embedded
# in a string literal.
IFS=$'\n' read -d '' -ra args <<<"$(xargs -n 1 printf '%s\n' <<<"$line")"

# Now pass the array to the `print` function.
print "${args[@]}"

结果:

[1]
[double-quoted string]
[*]
[single-quoted string]
[string-with-;|>-(metachars)]

注意事项和限制:

  • 不带引号的 token 允许使用 \转义嵌入字符,例如空格、单引号和双引号。

    • 但是,\其他字符之前被忽略,这可能是不受欢迎的;例如:echo 'a\b' | xargs # -> 'ab' - 要么使用 \\ ,或者用单引号或双引号来代替标记。
  • 引用的标记不需要内部 \ -转义,但遗憾的是,不支持嵌入相同类型的引号 - 转义似乎不起作用。

  • 请注意指定 printf '%s\n'作为 xargs 执行的命令通常没有必要,因为 xargs默认调用echo实用程序(不是内置的 shell);然而,一些echo实现可以识别自己的选项,例如 -e (虽然不支持 -- ),因此第一个输出标记可能会被误认为是选项。
    相比之下,printf '%s\n适用于所有情况。

  • 不支持引用具有嵌入换行符的字符串。 ( xargs 在这种情况下报告解析错误) - 据推测,这很少会成为问题。

关于bash - 将字符串传递给带有空格的 bash 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22591272/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com