When not to quote a command substitution?
Answer: When you want the output of the command substitution to be treated as separate arguments.
Example:
We want to extract specific packets (packet numbers 1, 5, 10 and 20) from a .pcap
file. The relevant command is the following:
editcap -r capture.pcap select.pcap 1 5 10 20
(Source to the command)
Now, we want to extract random packets from the file. To do that, we will use shuf
from GNU Coreutils.
shuf -i 0-50 -n 4
8
24
20
31
The command above has generated 4 random numbers between 0 and 50.
Using it with editcap
:
editcap -r source.pcap select.pcap "$(shuf -i 0-50 -n 4)"
editcap: The specified packet number "1
34
4
38" isn't a decimal number
As you can see, quoting the command substitution has resulted in the output string of the shuf
to be treated as a single big string, including the newlines and whatnot as well. That is, putting quotes has resulted in the equivalent of the following command:
editcap -r source.pcap select.pcap "1
34
4
38"
Instead, we want Bash the chop the output of shuf
and insert this chopped output as separate arguments to editcap
. Omitting the quotes accomplishes that:
editcap -r source.pcap select.pcap $(shuf -i 0-50 -n 4)