Linux 使用标准工具对整个参数数组进行转义,以便在类似sh的shell中使用

Linux 使用标准工具对整个参数数组进行转义,以便在类似sh的shell中使用,linux,bash,shell,escaping,sh,Linux,Bash,Shell,Escaping,Sh,我正在寻找一个标准工具,它能够获取所有参数并将其转换为单个字符串,适合在自动生成的bash/sh/zsh脚本中用作多个参数。这样的命令在各种符文学科中都非常有用。其用法示例如下: % shsafe 'A big \nasty string '\'' $HOME $PATH' 'another string \\' 'A big \nasty string '\'' $HOME $PATH' 'another string \\' 在另一个脚本中使用它: % sshc host rm 'file

我正在寻找一个标准工具,它能够获取所有参数并将其转换为单个字符串,适合在自动生成的bash/sh/zsh脚本中用作多个参数。这样的命令在各种符文学科中都非常有用。其用法示例如下:

% 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扩展,除了
'
本身

shsafe

#!/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'
这是一个有点容易出错的地方,引用无处不在,所以这不是理想的,我想,但这是一个坚实的解决方案,应该在任何地方工作。如果它被大量使用,您可以将其转换为shell函数:

shsafe () {
    printf "$'%q' " "$@"
}

printf“%q”arg1 arg2
<代码>打印“%q”arg1 arg2“?我想到了这一点。即使使用空格,arg1和arg2也将被视为相同的参数,用空格分隔<不过,代码>printf'$'\''%q'\''arg1 arg2确实有效。不过,它极易出错,每次都要输入。我不认为这是一个很好的解决方案,因为它,即使它只使用标准工具。你的意思是<代码> $''%q’'/COD>?您希望字符串在打印时的外观如何?xargs是否解决了您的问题?不,这是不同的,@nopasara
manxargs
了解它的功能。POSIX不需要支持
$'…'
%q