linux - 使用标准工具转义整个参数数组,以便在类似 sh 的 shell 中使用

标签 linux bash shell escaping sh

我正在寻找一种标准工​​具,该工具能够获取其所有参数并将其转换为适合在自动生成的 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/

相关文章:

linux - 创建一个 shell,使用 curl 在 dropfile.to 上下载文件

linux - Unix命令搜索文件中的一行并替换它

python - 使用 Python 创建的文件被写入错误的目录

c - 在我的读取函数 myread 中,当我执行 cat/driver/mydriver 时,它会不断打印读取的数据。我只需要打印一次如何做到这一点

php - 如果尚不存在,如何在 WordPress 中创建文件夹?

linux - Linux 中基于扩展名的颜色代码文件

linux - sort -um 是否仍然保证唯一性?

c - 如何将变量传递给 C 中的 shell 命令?

bash - 如果其子 shell 错误,则导致 bash 语句出错

shell - 无法使用docker run将命令行参数传递给Shell脚本文件