27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 14. Command Substitution<br />

Command substitution reassigns the output of a command [44] or even multiple commands; it literally plugs<br />

the command output into another context.<br />

The classic form of command substitution uses backquotes (`...`). Commands within backquotes (backticks)<br />

generate command line text.<br />

script_name=`basename $0`<br />

echo "The name of this script is $script_name."<br />

The output of commands can be used as arguments to another command, to set a variable, and even for<br />

generating the argument list in a for loop.<br />

rm `cat filename` # "filename" contains a list of files to delete.<br />

#<br />

# S. C. points out that "arg list too long" error might result.<br />

# Better is xargs rm −− < filename<br />

# ( −− covers those cases where "filename" begins with a "−" )<br />

textfile_listing=`ls *.txt`<br />

# Variable contains names of all *.txt files in current working directory.<br />

echo $textfile_listing<br />

textfile_listing2=$(ls *.txt)<br />

echo $textfile_listing<br />

# Same result.<br />

# The alternative form of command substitution.<br />

# A possible problem with putting a list of files into a single string<br />

# is that a newline may creep in.<br />

#<br />

# A safer way to assign a list of files to a parameter is with an array.<br />

# shopt −s nullglob # If no match, filename expands to nothing.<br />

# textfile_listing=( *.txt )<br />

#<br />

# Thanks, S.C.<br />

Command substitution may result in word splitting.<br />

COMMAND `echo a b`<br />

# 2 args: a and b<br />

COMMAND "`echo a b`" # 1 arg: "a b"<br />

COMMAND `echo`<br />

COMMAND "`echo`"<br />

# no arg<br />

# one empty arg<br />

# Thanks, S.C.<br />

Even when there is no word splitting, command substitution can remove trailing newlines.<br />

# cd "`pwd`" # This should always work.<br />

# However...<br />

mkdir 'dir with trailing newline<br />

Chapter 14. Command Substitution 236

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!