Bash Script Tutorial: Command Substitution

command-line-blogImageIn this tutorial we’ll take a look at Command Substitution. Command substitution allows us to reassign the output of a command to a variable instead of printing it to the screen. Also, we can insert the output of command substitution into another context like: name of a file or some other text. When using command substitution is a good practice to test the command output to the screen before assign to a variable. That way we make sure we’re getting the right output. In order to use command substitution we place our commands between ‘$( )’ dollar sign and parenthesis. The output of all commands within command substitution gets resign instead of sent to stdout. So let’s see some examples of command substitution done in the terminal.

Assign filename to variable file
Always test your command with stdout before using it

ls -1 file1.jpg
file=$(ls -1 file1.jpg)
echo $file

creating an array of directory content

ls -1
dir_content=($(ls -1))
echo ${dir_content[@]}

command substitution in stdout

date +%A
echo “today is $(date +%A)today=$(date +%A)
echo $today

creating a directory with date embedded in name

mkdir pictures-$(date +%F)

creating a log file with date embedded in name

ping -c 1 > yahoo-connection-$(date +%F).log

backup data and using command substitution

tar -cvzf $(date +%F)-test-backup.tar.gz test/

getting available disk space and assign to variable

df -h /dev/sda1 | grep dev | awk '{print $4}' 
available_space=$(df -h /dev/sda1 | grep dev | awk '{print $4}')
echo $available_space

extracting today’s log from “auth.log” log file

grep “$(date | awk '{print $2,$3}')/var/log/auth.log
Share This!

Leave a Reply

Your email address will not be published.