bash 在命令替换中使用变量

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

Use Variable in Command Substitution

bash

提问by Tobias Timpe

I need some help with the following simple bash script, where the variable idoes not seem to get substituted when running curl(causing an error).

我需要以下简单 bash 脚本的帮助,其中变量i在运行时似乎没有被替换curl(导致错误)。

(This is just a simple abstraction of the actual script)

(这只是对实际脚本的简单抽象)

for i in {1..3}
do
  HTML=$(curl -s 'http://example.com/index.php?id=$i')
done;

回答by nosid

Variables are not substituted within single quotes. You have to use double quotes in this case:

变量不会被单引号替换。在这种情况下,您必须使用双引号:

for i in {1..3}; do
    HTML=$( curl -s "http://example.com/index.php?id=$i" )
done

回答by amadain

From http://tldp.org/LDP/abs/html/varsubn.html

来自http://tldp.org/LDP/abs/html/varsubn.html

Enclosing a referenced value in double quotes (" ... ") does not interfere with variable substitution. This is called partial quoting, sometimes referred to as "weak quoting." Using single quotes (' ... ') causes the variable name to be used literally, and no substitution will take place. This is full quoting, sometimes referred to as 'strong quoting.'

将引用的值括在双引号 (" ... ") 中不会干扰变量替换。这称为部分引用,有时也称为“弱引用”。使用单引号 (' ... ') 会导致按字面使用变量名称,并且不会发生替换。这是完整引用,有时也称为“强引用”。

A

一种