如何引用带有大量“和”的字符串?

时间:2017-10-13 09:12:12

标签: shell

我需要运行这样的函数:

process_del_netdevice()
{
    curl "http://127.0.0.1:8080${1}monitor" --header \
        "Content-Type: application/json" --header \
        "x-auth-token: $AUTH_TOKEN" -d '{"cmd": "device_del netdev-'$2'"}'

    curl "http://127.0.0.1:8080${1}monitor" --header \
        "Content-Type: application/json" --header \
        "x-auth-token: $AUTH_TOKEN" -d '{"cmd": "netdev_del '$2'"}'

    curl "http://127.0.0.1:8080${1}monitor" --header \
        "Content-Type: application/json" --header \
        "x-auth-token: $AUTH_TOKEN" -d '{"cmd": "chardev-remove char-'$2'"}'
}

但是我需要输出我运行的命令,所以我想要这样的代码:

process_del_netdevice()
{
    res="curl "http://127.0.0.1:8080${1}monitor" --header \
        "Content-Type: application/json" --header \
        "x-auth-token: $AUTH_TOKEN" -d '{"cmd": "device_del netdev-'$2'"}'"

    echo $res
}

但是提醒我错误,那么如何回应我运行的这个命令?谢谢〜

3 个答案:

答案 0 :(得分:1)

这可以正确引用,但这将变得非常难以理解。我会建议第二个执行打印和执行的功能。

execute_and_print() {
  "$@"
  printf '%q ' "$@"
  printf '\n'
}

并在您的代码中:

    process_del_netdevice()
    {
    execute_and_print curl "http://127.0.0.1:8080${1}monitor" --header \
        "Content-Type: application/json" --header \
        "x-auth-token: $AUTH_TOKEN" -d '{"cmd": "device_del netdev-'$2'"}'

    execute_and_print curl "http://127.0.0.1:8080${1}monitor" --header \
        "Content-Type: application/json" --header \
        "x-auth-token: $AUTH_TOKEN" -d '{"cmd": "netdev_del '$2'"}'

    execute_and_print curl "http://127.0.0.1:8080${1}monitor" --header \
        "Content-Type: application/json" --header \
        "x-auth-token: $AUTH_TOKEN" -d '{"cmd": "chardev-remove char-'$2'"}'
}

正确引用也可以通过以下方式实现:

for param in "$@"; do
  printf "'%s' " "$(printf '%s' "$param" | sed -e "s/'/'\\\\''/g")"
done
printf '\n'

答案 1 :(得分:1)

使用set -x启用命令记录,set +x将其关闭。

答案 2 :(得分:0)

首先 - 如果您只需要记录,请使用public static Bitmap getRotatedBitmap(Bitmap bm, float degree) { Bitmap bitmap = bm; if (degree != 0) { Matrix matrix = new Matrix(); matrix.preRotate(degree); // if(shouldFlip) // matrix.preScale(-1,1); bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true); } return bitmap; } 启用shell的内置日志记录功能;它是工作的正确工具。

要生成反映命令文本的shell引用字符串,您可以使用bash和ksh扩展名set -x,也可以依赖提供此类功能的第三方脚本语言。那么考虑一下:

printf '%q'

...或...

# needs Python, supported on all POSIX-y shells, output works on all POSIX shells
print_quoted() {
  python -c 'import sys, pipes; print(" ".join(pipes.quote(x) for x in sys.argv[1:]))' "$@"
}

一旦您选择了上述其中一项,很容易纳入其他地方:

# More efficient; needs bash or ksh; unusual inputs may result in outputs that only work
# on the same shell (ie. $''-quoted strings).
print_quoted() {
  printf '%q ' "$@"
  printf '\n'
}