Bash How to Assign Output to Variable

Bash How to Assign Output to Variable

Backquotes (“) are used for command substitution.

var=`date`

Command “date” return date to variable “var”. The alternative method to using command substitution is “$()”:

var =$(date)

If we want to get value from “var” use “$var”:

echo "$var"

Output: Tue Jul 12 15:33:06 CEST 2016

It properly always uses double quotes around variable substitution. Without double quotes, the variable is expanded which may cause problems if the variable contains special characters.

Make sure there is no space between variable name before and after assign char (=). You can assign output from pipeline to a variable:

NUM_FILES=`ls | wc -l`

Leave a Comment