Here is the video version, if you prefer it:
You can take a result of a command and store it in a variable or use the result of that first command as an argument for another command. This is called command substitution. (Ward, 2014)
Here is an example of command substitution in a sample script:
#!/bin/bash
LINES=$(grep 'a' aba.txt)
for word in $LINES
do
echo $word
done
We first take every line that has the character a
in the file aba.txt
and then we store it in the variable LINES
. Then we iterate over each word in the variable LINES
and we print it. Why does LINES
contain words, not lines? It contains lines indeed, but words that make up those lines are separated by a space (you can see so yourself by putting echo $LINES
just before the for
loop) and since each space is interpreted as a delimiter in a sequence, we get individual words.
Here is the output (along with aba.txt
contents):
mislav@mislavovo-racunalo:~/Linux_folder$ cat aba.txt
Mustard is how we transfer wealth
Some stuff Abba Mustard
Mustard Mustard
Mustard Mustard
It's the Mustard
In the Rich Man's World
AB
Mustard is how we transfer wealth
Ab
aB
ab
mislav@mislavovo-racunalo:~/Linux_folder$ ./tutorialScript.sh
Mustard
is
how
we
transfer
wealth
…
A simple example of using the result of the first command as an input to another command is echo $(ls)
. We use the output of ls
and we echo
it.
Thank you for reading!
References
Ward, B. (2014). How Linux Works: What Every Superuser Should Know (2nd ed.). No Starch Press. Pages 263-264