Handling quoting and escaped spaces in Bash command arguments

☆樱花仙子☆ 提交于 2019-12-01 12:32:22

It's really this simple:

your_command "$filename_with_spaces_maybe" -opt1 "$some_words" -opt2 "$a_number" -opt3 "$a_file_reference" -opt4 "$several_sentences"

That is to say:

  • Put every parameter expansion (where a variable name is replaced with its value) in double quotes -- even if you think the value will only be numeric.
  • Don't bother with any kind of eval, or assignment, etc.

The only quotes required are syntactic, not literal -- "nested" or "escaped" quotes are literal characters without syntactic meaning, so they have no effect on parsing (without an additional parse step, as generated by eval, which is indeed bad practice when at all avoidable), and just add extra unwanted content to the command actually being run.


For cases when you think you need to store a command in a variable for other reasons (to add arguments only conditionally, or to be able to reuse it), see BashFAQ #50.

If you weren't already convinced that eval is a Bad Idea, you'd want to read BashFAQ #48.

The Wooledge page on Quotes is an excellent resource for this question in general.

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