我正在寻找一种标准工具,该工具能够获取其所有参数并将其转换为适合在自动生成的 bash/sh/zsh 脚本中用作多个参数的单个字符串。这样的命令在 script-fu 的各个学科中都非常有用。其用法示例:
% shsafe 'A big \nasty string '\'' $HOME $PATH' 'another string \\'
'A big \nasty string '\'' $HOME $PATH' 'another string \\'
在另一个脚本中使用它:
% sshc host rm 'file/with spaces and $special chars'
sshc
包含
#!/bin/bash
# usage: sshc host command [arg ...]
# Escapes its arguments so that the command may contain special
# characters. Assumes the remote shell is sh-like.
host=$1
shift
exec ssh "$host" "$(shsafe "$@")"
另一个例子:
#!/bin/bash
# Run multiple commands in a single sudo session. The arguments of
# this script are passed as arguments to the first command. Useful if
# you don't want to have to type the password for both commands and
# the first one takes a while to run.
sudo bash -c "pacman -Syu $(shsafe "$@") && find /etc -name '*.pacnew'"
我在预先存在的命令中找不到合适的解决方案来解决这个问题,所以我自己编写了一个名为 shsafe
的命令。它使用单引号 ''
完全关闭所有 shell 扩展,'
本身除外。
安全
:
#!/usr/bin/env python
from sys import *
n = len(argv)
if n == 1:
exit(0)
i = 1
while True:
stdout.write("'" + argv[i].replace("'", "'\\''") + "'")
i += 1
if i == n:
break
stdout.write(' ')
stdout.write('\n')
是否有任何标准工具能够对其参数执行此操作?
请注意,带有仅由 %q 格式化程序组成的格式字符串的 printf 命令对此不够好,因为它不会将多个参数分开:
% printf %q arg1 arg2
arg1arg2
最佳答案
我最终想出了一个不错的方法:
% printf "$'%q' " 'crazy string \ $HOME' 'another\ string'
$'crazy\ string\ \\\ \$HOME' $'another\\\ string'
到处都是引号有点容易出错,所以它并不理想,IMO,但它是一个可靠的解决方案,应该适用于任何地方。如果它被大量使用,你总是可以把它变成一个 shell 函数:
shsafe () {
printf "$'%q' " "$@"
}
关于linux - 使用标准工具转义整个参数数组,以便在类似 sh 的 shell 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40461908/