Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Variable in Command Substitution

Tags:

bash

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

(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;
like image 571
Tobias Timpe Avatar asked Aug 09 '13 06:08

Tobias Timpe


People also ask

How do you use variables in Bash commands?

Using variable from command line or terminal You don't have to use any special character before the variable name at the time of setting value in BASH like other programming languages. But you have to use '$' symbol before the variable name when you want to read data from the variable.

Which command is used for command substitution?

Command substitution allows you to capture the output of any command as an argument to another command. You can perform command substitution on any command that writes to standard output. The read special command assigns any excess words to the last variable.

How do you call a variable in a shell script?

Unix Command Course for Beginners In this chapter, we will learn how to use Shell variables in Unix. A variable is a character string to which we assign a value. The value assigned could be a number, text, filename, device, or any other type of data. A variable is nothing more than a pointer to the actual data.


2 Answers

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
like image 169
nosid Avatar answered Oct 13 '22 18:10

nosid


From 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

like image 30
amadain Avatar answered Oct 13 '22 16:10

amadain