Friday, May 10, 2013

Command Substitution
$(command)

Introduction

Bash Command Substitution allows you to replace $(command) with the result of the command, usually in a script.

So wherever $(command) is found its output is substituted prior to interpretation by the shell.


HCSIZE=$(wc -l ~/bashrc)

or

HCSIZE=`wc -l ~/bashrc`


Note these are BackTicks / backquotes ` not single quotes '

The BackTick key is normally the top left hand key on a US English keyboard.

The above command creates a new variable $HCSIZE that is equal to the number of lines in your bashrc file.

The second (and older) version allows the backslash \ character to escape

1. Dollar symbol $
2. Backquote `
3. Another backslash \

The $(command) syntax avoids this complexity by treating all characters between the brackets literally.



BackTicks

BackTicks ` ` are a common method of Command Substitution.

Command Substitution allows you to use the results of a command in a shell script.

To use Command Substitution put the command you want to use between BackTicks.

echo "today is `date +%d-%m-%y` "
today is 27-09-10 
or alternatively
TODAY=`date +%d-%m-%y`
echo "today is $TODAY "
today is 27-09-10 



Further Reading



Beginning the Linux Command Line 2009 APress.
Chapter 14: Introduction to Bash Shell Scripting pages 319 - 351.




See Page 357 LPI Linux Certification in a Nutshell by Jeffrey Dean, O'Reilly.

See An LPI Level 1 Crash Course for more details on the above book.


No comments:

Post a Comment