Preserving escapes in bash arguments $@

南笙酒味 提交于 2019-11-30 19:27:03

问题


related to this: Preserve Quotes in bash arguments

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

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.


回答1:


You need to use an array.

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

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

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).



来源:https://stackoverflow.com/questions/21820240/preserving-escapes-in-bash-arguments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!