如何在 Bash 脚本中传递带有空格的命令行参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11870325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:57:24  来源:igfitidea点击:

How to pass command line argument with space in Bash scripts

bashcommand-line-arguments

提问by Richard

Let's say there is one script s1, and I need to pass argument $1with value foo bar, with space in it. This can be done

假设有一个 script s1,我需要传递$1带有 value 的参数foo bar,其中有空格。这是可以做到的

./s1 "foo bar"

./s1 "foo bar"

however, when I want to run the above command in another script (say s2), how should I put it? If I put it as above, foo barwill be interpreted as two arguments (to s1) rather than one.

但是,当我想在另一个脚本中运行上述命令时(比如s2),我应该怎么写?如果我把它放在上面,foo bar将被解释为两个参数(到 s1)而不是一个。

回答by cnicutar

You can try quoting $1:

您可以尝试引用$1

./s2 ""

回答by phoxis

Use single quotes.

使用单引号。

./script 'this is a line'

./script 'this is a line'

To consider variable substitutions use double quotes

考虑变量替换使用双引号

./script "this is a line"

./script "this is a line"

回答by kch

How about:

怎么样:

./s1 foo\ bar

Would that work?

那行得通吗?