You can use the grep command for any given input files, selecting lines that match one or more patterns. By default the output shown on screen. But, you can store output to variable in your shell scripts.
Syntax: Command substitution
Command substitution means nothing more but to run a shell command and store its output to a variable or display back using echo command. The syntax is:
VAR=`command-name` VAR="`grep word /path/to/file`" ## or ## VAR=$(command-name) VAR="$(grep word /path/to/file)"
To display date and time using echo command:
echo "Today is $(date)" ## or ## echo "Today is `date`"
You can store command output to a shell variable using the following syntax:
To store current date and time to a variable called todays:
You can display value of $todays, enter:
In this example use grep command to search for a username called vivek and store output to a variable called myuser:
myuser="$(grep '^vivek' /etc/passwd)" echo "$myuser"
You can store the output of a grep command in a variable at the same time as printing the output using the following tee command based syntax:
foo="$(grep '^vivek' /etc/passwd | tee /dev/tty) " echo "$foo"
This is useful to direct output from a grep command to the shell variable and display on screen at the same time.Share this tutorial on: