User Tools

Site Tools


ubuntu:bash:assign_output_of_shell_command_to_variable

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
ubuntu:bash:assign_output_of_shell_command_to_variable [2019/11/28 23:15] peterubuntu: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=$(/path/to/command) 
-var=$(/path/to/command arg1 arg2) 
-</code> 
- 
-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=`/path/to/command` 
-var=`/path/to/command arg1 arg2` 
-</code> 
- 
-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) 
-</code> 
- 
-OR 
- 
-## alternate syntax ## 
-<code bash> 
-now=`date` 
-</code> 
- 
----- 
- 
-To display back result (or output stored in a variable called $now) use the echo or printf command: 
- 
-<code bash> 
-echo "$now" 
-printf "%s\n" "$now" 
-</code> 
- 
-Sample outputs: 
- 
-<code bash> 
-Wed Apr 25 00:55:45 IST 2012 
-</code> 
- 
----- 
- 
-You can combine the echo command and shell variables as follows: 
- 
-<code bash> 
-echo "Today is $now" 
-</code> 
- 
-Sample outputs: 
- 
-<code bash> 
-Today is Wed Apr 25 00:55:45 IST 2012 
-</code> 
- 
----- 
- 
-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" "$(date)" 
-</code> 
- 
-Sample outputs: 
- 
-<code bash> 
-Today is Wed Apr 25 00:57:58 IST 2011 
-</code> 
- 
- 
----- 
- 
-===== Use Multiline Command ===== 
- 
- 
-Try the following syntax: 
- 
-<code bash> 
-my_var=$(command \ 
-arg1 \ 
-arg2 \ 
-arg3 ) 
-echo "$my_var" 
- 
----- 
- 
-===== Example using Date ===== 
- 
-<code bash> 
-OUT=$(date \ 
---date='TZ="America/Los_Angeles" 09:00 next Thu') 
-echo "$OUT" 
-<code bash> 
- 
----- 
- 
-===== Example using Ping ===== 
- 
-<code bash> 
-#!/bin/bash 
-_ping="/bin/ping" 
-domain="www.cyberciti.biz" 
-  
-ping_avg="$(${_ping} \ 
--q \ 
--c 4 \ 
-${domain} | grep rtt)" 
-  
-echo "Avg ping time for ${domain} : ${ping_avg}" 
-</code> 
  
ubuntu/bash/assign_output_of_shell_command_to_variable.1574982907.txt.gz · Last modified: 2020/07/15 09:30 (external edit)

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki