Shell Script Command Substitution
- Process of assigning the built-in linux command into a variable is called as command substitution
- This is done by using two approaches. They are:
- Using $(command expression)
- Using back ticks `command expression`
Approach 1
- It is based on the $ symbol followed by () operator.
Syntax
variable-name=$(command expression)
Example
k=$(date)
- Here, the output of ls command is stored to the user defined variable ‘k’.
NOTE
- In linux shell, by default the variable is global. So no need to use any keyword like global
- Also shell is a dynamic typed language. So no need to use any specific type like int, float, char in the declaration of variable / method.
Approach 2
- It is based on the back tick symbol ` `
Syntax
variable-name=`command expression`
Example
k=`date`
I. EXAMPLE OF LISTING FILES AND SUB FOLDERS OF CURRENT DIRECTORY VIA COMMAND SUBSTITUTION
SOURCE CODE
echo “—————————————————–“
echo -e “\tListing Files via Command Substitution with for loop”
echo “—————————————————–“
# command substitution (using approach 1)
files=$(ls)
# iterate the loop
for i in $files
do
echo $i
done
OUTPUT
RELATED POSTS
1. Strings in Bash Script
2. Arrays in Bash Script
3. Function in Bash Script
4. Switch Case in Bash Script
5. For Loop in Shell Script (4 Types)
6. Operators in Bash Script
7. Command Line Arguments in Shell Script
8. File Test Operators in Bash Script
9. Read File Line by Line
MORE USEFUL TUTORIALS