How to save the output of a command to a variable in Bash script?
In Bash
getting the output of a command line in terminal is sometimes necessary when
doing Bash/Shell script.
For
example, if need to monitor a specific service whether it is installed, running
or disabled. Getting the output of the command that checks the status of specific
service is quite important, so the script will know on what to execute.
If the
specific output shows that the service has stopped then the script can decide
to start the service, or if the output shows that a specific service or
software is not installed then an option to install the software can be done.
Here’s an
example on how to save the status of a specific output to a variable using
Bash.
#!/bin/bash
dcommand=$(systemctl status gdm.service)
command_output=$(echo "$dcommand")
str_running='Active: active (running)'
if [[ "$command_output" == *"$str_running"* ]]; then
echo "It's there, gdm.service is
running."
#else
#do
something here if not running
#a chain of commands can be done by doing like ths:
#command1;command2;sleep 3;command3
#command 2 will not execute unless command 1 is done
fi
The trick
is on this line:
dcommand=$(systemctl
status gdm.service) --- replace this line with any commands
command_output=$(echo "$dcommand")
--- the echo will execute the command and output is save to variable on
the left
Full script:
That’s
it..till next time.. Enjoy scripting.. Cheers!
================================
Heaven's Dew Fall Prayer app for Android :
https://play.google.com/store/apps/details?id=com.myrosaryapp
Comments
Post a Comment