Difference between revisions of "Command substitution"

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to navigation Jump to search
(Created page with ' Category:Control flow loop')
 
Line 1: Line 1:
 
+
Command substitution is nothing but run a shell command and store it's output to a variable or display back using [[echo command]]. For example, display date and time:
[[Category:Control flow loop]]
+
<source lang="bash">echo "Today is $(date)"</source>
 +
OR
 +
<source lang="bash">echo "Computer name is $(hostname)"</source>
 +
==Syntax==
 +
You can use the grave accent (`) to perform a command substitution. The syntax is:
 +
<pre>`command-name`</pre>
 +
OR
 +
<pre>$(command-name)</pre>
 +
===Command substitution in an echo command===
 +
<source lang="bash">echo "Text $(command-name)"</source>
 +
OR
 +
<source lang="bash"> echo -e "List of logged on users and what they are doing:\n $(w)"</source>
 +
Sample outputs:
 +
<pre>List of logged on users and what they are doing:
 +
  09:49:06 up  4:09,  3 users,  load average: 0.34, 0.33, 0.28
 +
USER    TTY      FROM              LOGIN@  IDLE  JCPU  PCPU WHAT
 +
vivek    tty7    :0              05:40    ?    9:06m  0.09s /usr/bin/gnome-
 +
vivek    pts/0    :0.0            07:02    0.00s  2:07m  0.13s bash
 +
vivek    pts/2    :0.0            09:03  20:46m  0.04s  0.00s /bin/bash ./ssl
 +
</pre>
 +
[[Category:Control flow loop]][[Category:Commands]]

Revision as of 04:19, 14 September 2009

Command substitution is nothing but run a shell command and store it's output to a variable or display back using echo command. For example, display date and time:

echo "Today is $(date)"

OR

echo "Computer name is $(hostname)"

Syntax

You can use the grave accent (`) to perform a command substitution. The syntax is:

`command-name`

OR

$(command-name)

Command substitution in an echo command

echo "Text $(command-name)"

OR

 echo -e "List of logged on users and what they are doing:\n $(w)"

Sample outputs:

List of logged on users and what they are doing:
  09:49:06 up  4:09,  3 users,  load average: 0.34, 0.33, 0.28
USER     TTY      FROM              LOGIN@   IDLE   JCPU   PCPU WHAT
vivek    tty7     :0               05:40     ?     9:06m  0.09s /usr/bin/gnome-
vivek    pts/0    :0.0             07:02    0.00s  2:07m  0.13s bash
vivek    pts/2    :0.0             09:03   20:46m  0.04s  0.00s /bin/bash ./ssl