回显带有变量的单行 bash 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16825158/
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 05:33:12  来源:igfitidea点击:

echo a one-liner bash script with variables

bashecho

提问by tflutre

I would like to do that:

我想这样做:

i="1"; echo -e '#!/usr/bin/env bash\nmyprogram -i "input_${i}.txt"'

and pipe it to a job scheduler.

并将其通过管道传输到作业调度程序。

However, this doesn't replace the variable i by its value. Instead, I obtain this:

但是,这不会用它的值替换变量 i。相反,我得到了这个:

#!/usr/bin/env bash
myprogram -i "input_${i}.txt"

I played a bit with option -e of echo and with single-/double-quote but could not make it work. For instance, I get this:

我用选项 -e of echo 和单/双引号玩了一点,但无法使其工作。例如,我得到这个:

i="1"; echo -e "#!/usr/bin/env bash\nmyprogram -i \"input_${i}.txt\""
-bash: !/usr/bin/env: event not found

My bash version is 4.1.2.

我的 bash 版本是 4.1.2。

回答by Ansgar Wiechers

Try this:

尝试这个:

i="1"; echo -e '#!/usr/bin/env bash\nmyprogram -i '"\"input_${i}.txt\""

You can echosingle- and double-quoted strings at the same time.

您可以同时使用echo单引号和双引号字符串。

回答by Has QUIT--Anony-Mousse

Try also escaping the exclamation mark:

也尝试转义感叹号:

\!should be okay, and will not be read as an "event" by bash.

\!应该没问题,并且不会被 bash 解读为“事件”。

回答by Mark Reed

i="1"; echo -e '#!/usr/bin/env bash\nmyprogram -i "input_'"${i}"'.txt"'

Basically, use single quotes until you need to interpolate, then close the single quotes, open the double quotes, add the interpolation, close the double quotes, reopen single quotes, and finish the string. In the shell, quotation marks don't delimit a word; they just change the interpretation of the part of a word falling between them.

基本上,使用单引号直到需要插值,然后关闭单引号,打开双引号,添加插值,关闭双引号,重新打开单引号,并完成字符串。在 shell 中,引号不分隔单词;他们只是改变了他们之间的单词部分的解释。