ubuntu:bash:assign_output_of_shell_command_to_variable
Differences
This shows you the differences between two versions of the page.
Next revision | Previous revision | ||
ubuntu:bash:assign_output_of_shell_command_to_variable [2019/11/28 23:09] – created peter | ubuntu:bash:assign_output_of_shell_command_to_variable [2019/12/07 01:33] (current) – removed peter | ||
---|---|---|---|
Line 1: | Line 1: | ||
- | ====== Ubuntu - BASH - Assign Output of Shell Command To Variable ====== | ||
- | |||
- | To assign output of any shell command to variable in bash, use the following command substitution syntax: | ||
- | |||
- | <code bash> | ||
- | var=$(command-name-here) | ||
- | var=$(command-name-here arg1) | ||
- | var=$(/ | ||
- | var=$(/ | ||
- | </ | ||
- | |||
- | OR use backticks based syntax as follows to assign output of a Linux command to a variable: | ||
- | |||
- | <code bash> | ||
- | var=`command-name-here` | ||
- | var=`command-name-here arg1` | ||
- | var=`/ | ||
- | var=`/ | ||
- | </ | ||
- | |||
- | Do not put any spaces after the equals sign and command must be on right side of =. | ||
- | |||
- | |||
- | ---- | ||
- | |||
- | ===== Examples ===== | ||
- | |||
- | To store date command output to a variable called now, enter: | ||
- | |||
- | ## store date command output to $now ## | ||
- | <code bash> | ||
- | now=$(date) | ||
- | </ | ||
- | |||
- | OR | ||
- | |||
- | ## alternate syntax ## | ||
- | <code bash> | ||
- | now=`date` | ||
- | |||
- | ---- | ||
- | |||
- | To display back result (or output stored in a variable called $now) use the echo or printf command: | ||
- | |||
- | <code bash> | ||
- | echo " | ||
- | printf " | ||
- | </ | ||
- | |||
- | Sample outputs: | ||
- | |||
- | <code bash> | ||
- | Wed Apr 25 00:55:45 IST 2012 | ||
- | </ | ||
- | |||
- | ---- | ||
- | |||
- | You can combine the echo command and shell variables as follows: | ||
- | |||
- | <code bash> | ||
- | echo "Today is $now" | ||
- | </ | ||
- | |||
- | Sample outputs: | ||
- | |||
- | <code bash> | ||
- | Today is Wed Apr 25 00:55:45 IST 2012 | ||
- | </ | ||
- | |||
- | ---- | ||
- | |||
- | You can do command substitution in an echo command itself (no need to use shell variable): | ||
- | |||
- | <code bash> | ||
- | echo "Today is $(date)" | ||
- | printf "Today is %s\n" " | ||
- | </ | ||
- | |||
- | Sample outputs: | ||
- | |||
- | <code bash> | ||
- | Today is Wed Apr 25 00:57:58 IST 2011 | ||
- | </ | ||
- | |||
ubuntu/bash/assign_output_of_shell_command_to_variable.1574982568.txt.gz · Last modified: 2020/07/15 09:30 (external edit)