gpt4 book ai didi

escaping - 从 sh : Escaping 中生成 sh 代码

转载 作者:行者123 更新时间:2023-12-02 15:38:06 25 4
gpt4 key购买 nike

我有一个 shell 变量(我们将调用 x),其中包含一个带有 shell 元字符的字符串。例如,我可能有

abc  "def's"  ghi

设置为

x='abc  "def'\''s"  ghi'

我想从该字符串构建一个 shell 命令(存储在一个文件中,而不是执行)。我有哪些选择?

echo "prog $x"     >>file     # Doesn't work
echo "prog '$x'" >>file # Doesn't work
echo "prog \"$x\"" >>file # Doesn't work

当前解决方案使用sed

y=`echo "$x" | sed 's/\([^a-zA-Z0-9._\-\/]\)/\\\\\1/g'`
echo "prog $y" >>file

输出如下(虽然等效输出也是可以接受的):

prog abc\ \ \"def\'s\"\ \ ghi

问题是需要做这件事的地方越来越多。有没有人有更好的解决方案?

注意事项:

  • 必须适用于 sh(与 bash 相对)并且任何 sh 都可以合理地别名为(例如 bashsh 仿真模式下)。
  • 它必须尽可能便携(Windows 除外)。
  • perl 的使用是 Not Acceptable ,但使用随处可见 的其他 unix 工具可能是可接受的。

最佳答案

sh 有函数。

# to_shell_lit() - Creates a shell literal
# Usage: printf '%s\n' "...$( quote "..." )..."
to_shell_lit() {
printf \'
printf %s "$1" | sed "s/'/'\\\\''/g"
printf \'
}

测试:

$ x='abc  "def'\''s"  ghi'

$ printf '%s\n' "$x"
abc "def's" ghi

$ printf '%s\n' "prog `to_shell_lit "$x"`"
prog 'abc "def'\''s" ghi'

$ printf '%s\n' "prog $( to_shell_lit "`pwd`" )"
prog '/home/ikegami/foo bar'
$ printf '%s\n' "$( to_shell_lit "a'b" )"
'a'\''b'

$ printf '%s\n' "$( to_shell_lit '-n' )"
'-n'

$ printf '%s\n' "$( to_shell_lit '\\' )"
'\\'

$ printf '%s\n' "$( to_shell_lit 'foo
bar' )"
'foo
bar'

采用多个参数的版本:

# to_shell_lit() - Creates a shell literal
# Usage: printf '%s\n' "$( to_shell_lit "..." "..." "..." )"
to_shell_lit() {
local prefix=''
local p
for p in "$@" ; do
printf "$prefix"\'
printf %s "$p" | sed "s/'/'\\\\''/g"
printf \'
prefix=' '
done
}

关于escaping - 从 sh : Escaping 中生成 sh 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13354247/

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