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.

<strong>Advanced</strong> <strong>Bash−Scripting</strong> <strong>Guide</strong><br />

'<br />

cd 'dir with trailing newline<br />

'<br />

cd "`pwd`" # Error message:<br />

# bash: cd: /tmp/file with trailing newline: No such file or directory<br />

cd "$PWD"<br />

# Works fine.<br />

old_tty_setting=$(stty −g) # Save old terminal setting.<br />

echo "Hit a key "<br />

stty −icanon −echo<br />

# Disable "canonical" mode for terminal.<br />

# Also, disable *local* echo.<br />

key=$(dd bs=1 count=1 2> /dev/null) # Using 'dd' to get a keypress.<br />

stty "$old_tty_setting" # Restore old setting.<br />

echo "You hit ${#key} key." # ${#variable} = number of characters in $variable<br />

#<br />

# Hit any key except RETURN, and the output is "You hit 1 key."<br />

# Hit RETURN, and it's "You hit 0 key."<br />

# The newline gets eaten in the command substitution.<br />

Thanks, S.C.<br />

Using echo to output an unquoted variable set with command substitution removes trailing<br />

newlines characters from the output of the reassigned command(s). This can cause unpleasant<br />

surprises.<br />

dir_listing=`ls −l`<br />

echo $dir_listing<br />

# unquoted<br />

# Expecting a nicely ordered directory listing.<br />

# However, what you get is:<br />

# total 3 −rw−rw−r−− 1 bozo bozo 30 May 13 17:15 1.txt −rw−rw−r−− 1 bozo<br />

# bozo 51 May 15 20:57 t2.sh −rwxr−xr−x 1 bozo bozo 217 Mar 5 21:13 wi.sh<br />

# The newlines disappeared.<br />

echo "$dir_listing" # quoted<br />

# −rw−rw−r−− 1 bozo 30 May 13 17:15 1.txt<br />

# −rw−rw−r−− 1 bozo 51 May 15 20:57 t2.sh<br />

# −rwxr−xr−x 1 bozo 217 Mar 5 21:13 wi.sh<br />

Command substitution even permits setting a variable to the contents of a file, using either redirection or the<br />

cat command.<br />

variable1=`

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

Saved successfully!

Ooh no, something went wrong!