59
votes
Escape a variable for use as content of another script
Bash has a parameter expansion option for exactly this case:
${parameter@Q} The expansion is a string that is the value of parameter quoted in a format that can be reused as input.
So in this case:...
48
votes
Accepted
What does ${PATH:+:${PATH}} mean?
The :+ is a form of parameter expansion:
${parameter:+[word]} : Use Alternative Value.
If parameter is unset or
null, null shall be substituted; otherwise, the expansion of word (or
an ...
45
votes
Accepted
Bash variable substitution of variable followed by underscore
The command echo $BUILDNUMBER_ is going to print the value of variable $BUILDNUMBER_ which is not set (underscore is a valid character for a variable name as explicitly noted by Jeff Schaller)
You ...
43
votes
Is there any way to print value inside variable inside single quote?
You can't expand variables in single quotes. You can end single quotes and start double quotes, though:
echo 'visit:"'"$site"'"'
Or, you can backslash double quotes inside of double quotes:
echo "...
42
votes
Accepted
How to avoid space after bash variable in string?
Just enclose variable in braces:
echo -e "${Red}Note: blabla${NC}".
See more detail about Parameter Expansion.
See also great answer Why printf is better than echo? if you care about portability.
27
votes
Accepted
Bash variable substitution in a JSON string
JSON=\''{"hostname": "localhost", "outdir": "'"$OUTDIR"'", "port": 20400, "size": 100000}'\'
That is get out of the single quotes for the expansion of $OUTDIR. We did put that expansion inside double-...
26
votes
Is "${PS1-}" valid syntax and how does it differ from plain "$PS1"?
The variable expansion ${parameter:-word} will use the value of $parameter if it's set and non-null (not an empty string), otherwise it will use the string word.
Omitting the : will not test if the ...
Community wiki
23
votes
Accepted
Grep to find the correct line, sed to change the contents, then putting it back into the original file?
Try:
sed -i.bak '/firmware_revision/ s/test/production/' myfile.py
Here, /firmware_revision/ acts as a condition. It is true for lines that match the regex firmware_revision and false for other ...
23
votes
Accepted
Does bash support back references in parameter expansion?
ksh93 and zsh have back-reference (or more accurately1, references to capture groups in the replacement) support inside ${var/pattern/replacement}, not bash.
ksh93:
$ var='Blah: -> r1-ae0-2 / [...
23
votes
Accepted
Is it possible to print the content of the content of a variable with shell script? (indirect referencing)
You can accomplish this using bash's indirect variable expansion (as long as it's okay for you to leave out the $ from your reference variable):
$ var=test
$ test="my string"
$ echo "$var"
test
$ ...
21
votes
Escape a variable for use as content of another script
Bash provides a printf builtin with %q format specifier, which performs shell escaping for you, even in older (<4.0) versions of Bash:
printf '[%q]\n' "Ne'er do well"
# Prints [Ne\'er\ do\ well]
...
20
votes
Accepted
Append to PATH-like variable without creating leading colon if unset
You are on the right track with the ${:+} expansion operator, you just need to modify it slightly:
V=${V:+${V}:}new_V
The first braces expand to $V and the colon iff V is set already otherwise to ...
20
votes
Accepted
Bash echo $-1 prints hb1. Why?
You are not asking it to print the 1st argument, that would be: $1.
What you are asking for is a special parameter:
-
($-, a hyphen.) Expands to the current option flags as specified ...
19
votes
Accepted
See the expansion of Bash variables for debugging?
Run the script under bash -x:
$ bash -x script
+ DIR=/var/tmp
+ FILE=/var/tmp/file
+ SCRIPT_ROOT=/opt/root
+ TOOL=/opt/root/tool.sh
+ /opt/root/tool.sh /var/tmp/file
While -x is normally used for ...
18
votes
Append (alter) each array element via parameter expansion (i.e. without printf)?
Use $^array.
It turns the array into a sort of brace expansion of the array. As in when a=(foo bar baz), $^a would be a bit like {foo,bar,baz}.
$ a=(foo bar baz)
$ echo prefix${^a}suffix
...
18
votes
Accepted
Escape a variable for use as content of another script
TL;DR: skip to the conclusion.
While several shells/tools have builtin quoting operators some of which have already been mentioned in a few answers, I'd like to stress here that many are unsafe to use ...
18
votes
Accepted
Bash: Extract one of the four sections of an IPv4 address
Assuming the default value of IFS you extract each octet into it's own variable with:
read A B C D <<<"${IP//./ }"
Or into an array with:
A=(${IP//./ })
17
votes
Double and triple substitution in bash and zsh
#!/bin/bash
hello=world
echo=hello
echo $echo ${!echo}
17
votes
Accepted
What does the substitution ${!var_name+x} mean?
In the bash shell, ${!var} is a variable indirection. It expands to the value of the variable whose name is kept in $var.
The variable expansion ${var+value} is a POSIX expansion that expands to ...
16
votes
Accepted
Why do here-documents attempt shell substitution even on a commented line?
This is more general than bash. In POSIX shell, your EOF is referred to as a word, in the discussion of here-documents:
If no characters in word are quoted, all lines of the here-document shall be ...
15
votes
Variable with colon dash ${VAR:-}
The syntax ${VAR:-default} evaluates to the value of VAR or, if it is unset or null, it evaluates to the text after the hyphen (in this case, default); the syntax ${VAR- default} is similar shortened ...
15
votes
Accepted
Glob character within variable expands in bash but not zsh
That would be the first time I see anybody complaining about that (we more often see people complaining about it not doing word splitting upon parameter expansion).
Most people expect
echo $file
to ...
14
votes
How can I add datetime to an existing file name in Linux?
You have created a variable named _now, but later you reference a variable named _nowout. To avoid such issues, use curly braces to delimit variable names:
_now=$(date +"%m_%d_%Y")
_file="${_now}out....
13
votes
Is there any way to print value inside variable inside single quote?
When you deal with printing variable content, you should stick with printf instead of echo:
printf 'visit:%s\n' "$site"
will output visit: followed by content of $site and a newline regardless of ...
13
votes
Accepted
Is `echo $TEST` expanding an asterisk in the variable a bug?
No, it is not a bug. You have shown that
echo '*'
will produce a literal *. Hence when you substitute this output, as per the following command
TEST=$(echo '*')
it will put * into the variable $...
12
votes
Accepted
Is "${PS1-}" valid syntax and how does it differ from plain "$PS1"?
This is definitely POSIX syntax. Paraphrasing:
Using ${parameter-word}, if parameter is
set and not null, then substitute the value of parameter,
set but null, then substitute null, and
unset, then ...
12
votes
Bash variable substitution of variable followed by underscore
As George Vassiliou already explained, that's because you're printing the variable $BUILDNUMBER_ instead of $BUILDNUMBER. The best way to get what you want is to use ${BUILDNUMBER}_ as George ...
12
votes
Accepted
Word splitting in positional parameters
Word splitting only applies to unquoted expansions (parameter expansion, arithmetic expansion and command substitution) in modern Bourne-like shells (in zsh, only command substitution unless you use ...
11
votes
Is it possible to print the content of the content of a variable with shell script? (indirect referencing)
For the case when the variable name contained in var is prefixed with $ you may use eval:
$ var='$test'
$ test="my string"
$ eval echo $var
my string
What happens here:
bash expands $var to the ...
11
votes
Using parameter substitution on a Bash array
As far as I can see, there's no need to read it into a bash array to create that output:
$ sed 's/[ "]//g; s/,/ /; s/,//g; s/ /,/; s/.*/|ELEMENT|&|/' <file
|ELEMENT|10,this|
|ELEMENT|20,is|
|...
Only top scored, non community-wiki answers of a minimum length are eligible
Related Tags
variable-substitution × 290bash × 165
shell-script × 75
shell × 55
variable × 42
quoting × 24
zsh × 19
command-substitution × 15
wildcards × 14
sed × 13
awk × 12
string × 12
brace-expansion × 12
parameter × 10
scripting × 9
command-line × 8
ksh × 8
array × 8
find × 6
environment-variables × 6
arguments × 6
linux × 5
regular-expression × 5
filenames × 5
posix × 5