保存在bash参数中的转义$ @ [英] Preserving escapes in bash arguments $@

查看:144
本文介绍了保存在bash参数中的转义$ @的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与此相关:保留bash参数中的行情

一个简单的例子,我只需运行一个命令,使用 nohup ...

A simple example, where I simply run a command with nohup...

#!/bin/bash
nohup "$@"

...

./myscript gedit some\ file\ with\ spaces.txt

这个工作正常。但是,我不知道如何使用中间变量避免参数转义的正确位置。

This works fine. However, I have no idea how to keep the correct bits of the arguments escaped when using an intermediate variable...

#!/bin/bash
CMD="$@"
printf "%q\n" "$CMD" #for debugging
nohup $CMD

我已经尝试了一些排列,在所有情况下都没有任何作用。我失踪了什么理想情况下,我想在 nohup 之前修改 $ CMD

I've tried a few permutations and nothing works in all cases. What am I missing? Ideally I would like to be able to modify $CMD before nohup.

推荐答案

您需要使用数组。

cmd=( "$@" )
printf '%q\n' "${cmd[@]}"
nohup "${cmd[@]}"

标量变量(字符串)是NUL分隔的,因此它们不能包含参数列表(其性质是NUL分隔的)。

Scalar variables (strings) are NUL-delimited, so they can't contain an argument list (which is, by its nature, NUL-separated).

另请参见数组上的BashSheet条目 BashFAQ#5 (解释如何使用数组)和 BashFAQ#50 (解释由而不是以这种方式造成的陷阱)。

See also the BashSheet entry on arrays, BashFAQ #5 (explaining how to use arrays), and BashFAQ #50 (explaining the pitfalls caused by not doing it this way).

这篇关于保存在bash参数中的转义$ @的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆