Cari di Shell Script 
    Shell Script Linux Modules Tutorial
Daftar Isi
(Sebelumnya) 4. Introduction to Variables a ...6. Exit and Exit Status (Berikutnya)

Chapter 5. Quoting

Daftar Isi
5.1. Quoting Variables
5.2. Escaping

Quoting means just that, bracketing a string in quotes. Thishas the effect of protecting specialcharacters in the string from reinterpretationor expansion by the shell or shell script. (A characteris "special" if it has an interpretationother than its literal meaning. For example, the asterisk * representsa wild card character in globbing and Regular Expressions).

bash$ ls -l [Vv]*-rw-rw-r-- 1 bozo  bozo   324 Apr  2 15:05 VIEWDATA.BAT -rw-rw-r-- 1 bozo  bozo   507 May  4 14:25 vartrace.sh -rw-rw-r-- 1 bozo  bozo   539 Apr 14 17:11 viewdata.shbash$ ls -l '[Vv]*'ls: [Vv]*: No such file or directory

Certain programs and utilities reinterpret or expandspecial characters in a quoted string. An important use ofquoting is protecting a command-line parameter from the shell,but still letting the calling program expand it.

bash$ grep '[Ff]irst' *.txtfile1.txt:This is the first line of file1.txt. file2.txt:This is the First line of file2.txt.

Note that the unquoted grep [Ff]irst *.txt works under the Bash shell. [1]

Quoting can also suppress echo's "appetite" for newlines.

bash$ echo $(ls -l)total 8 -rw-rw-r-- 1 bo bo 13 Aug 21 12:57 t.sh -rw-rw-r-- 1 bo bo 78 Aug 21 12:57 u.shbash$ echo "$(ls -l)"total 8 -rw-rw-r--  1 bo bo  13 Aug 21 12:57 t.sh -rw-rw-r--  1 bo bo  78 Aug 21 12:57 u.sh

Notes

[1]

Unless there is a file named first in the current working directory. Yet another reason to quote. (Thank you, Harald Koenig, for pointing this out.


5.1. Quoting Variables

When referencing a variable, it is generally advisable toenclose its name in double quotes.This prevents reinterpretation of all special characters withinthe quoted string -- except $, `(backquote), and (escape). [1]Keeping $ as a special character withindouble quotes permits referencing a quoted variable("$variable"), that is, replacing thevariable with its value (see Example 4-1, above).

Use double quotes to prevent word splitting. [2]An argument enclosed in double quotes presentsitself as a single word, even if it contains whitespace separators.

List="one two three" for a in $List # Splits the variable in parts at whitespace.do  echo "$a" done# one# two# threeecho "---" for a in "$List"   # Preserves whitespace in a single variable.do # ^ ^  echo "$a" done# one two three

A more elaborate example:

variable1="a variable containing five words" COMMAND This is $variable1 # Executes COMMAND with 7 arguments:# "This" "is" "a" "variable" "containing" "five" "words" COMMAND "This is $variable1"  # Executes COMMAND with 1 argument:# "This is a variable containing five words" variable2="" # Empty.COMMAND $variable2 $variable2 $variable2 # Executes COMMAND with no arguments. COMMAND "$variable2" "$variable2" "$variable2" # Executes COMMAND with 3 empty arguments. COMMAND "$variable2 $variable2 $variable2" # Executes COMMAND with 1 argument (2 spaces). # Thanks, St�phane Chazelas.

Enclosing the arguments to an echostatement in double quotes is necessary only when word splittingor preservation of whitespaceis an issue.

Example 5-1. Echoing Weird Variables

#!/bin/bash# weirdvars.sh: Echoing weird variables.echovar="'(]{}$"" echo $var # '(]{}$" echo "$var"  # '(]{}$" Doesn't make a difference.echoIFS=''echo $var # '(] {}$"  converted to space. Why?echo "$var"  # '(]{}$" # Examples above supplied by Stephane Chazelas.echovar2=""" echo $var2   #   " echo "$var2" # " echo# But ... var2=""" is illegal. Why?var3=''echo "$var3" # # Strong quoting works, though.# ************************************************************ ## As the first example above shows, nesting quotes is permitted.echo "$(echo '"')"   # " # ^   ^# At times this comes in useful.var1="Two bits" echo "$var1 = "$var1""  # $var1 = Two bits# ^ ^# Or, as Chris Hiestand points out ...if [[ "$(du "$My_File1")" -gt "$(du "$My_File2")" ]]; then ...# ************************************************************ #

Single quotes (' ') operate similarly to doublequotes, but do not permit referencing variables, sincethe special meaning of $ is turned off.Within single quotes, every specialcharacter except ' gets interpreted literally.Consider single quotes ("full quoting") to be astricter method of quoting than double quotes ("partialquoting").

Since even the escape character ()gets a literal interpretation within single quotes, trying toenclose a single quote within single quotes will not yield theexpected result.

echo "Why can't I write 's between single quotes" echo# The roundabout method.echo 'Why can'''t I write '"'"'s between single quotes'# |-------|  |----------|   |-----------------------|# Three single-quoted strings, with escaped and quoted single quotes between.# This example courtesy of St�phane Chazelas.

Notes

[1]

Encapsulating "!" within double quotes gives an error when used from the command line. This is interpreted as a history command. Within a script, though, this problem does not occur, since the Bash history mechanism is disabled then.

Of more concern is the apparently inconsistent behavior of within double quotes, and especially following an echo -e command.

bash$ echo hello!hello!bash$ echo "hello!"hello!bash$ echo >bash$ echo "">bash$ echo aabash$ echo "a"abash$ echo xyxtybash$ echo "xy"xybash$ echo -e xyxtybash$ echo -e "xy"x   y  

Double quotes following an echo sometimes escape . Moreover, the -e option to echo causes the "" to be interpreted as a tab.

(Thank you, Wayne Pollock, for pointing this out, and Geoff Lee and Daniel Barclay for explaining it.)

[2]

"Word splitting," in this context, means dividing a character string into separate and discrete arguments.


5.2. Escaping

Escaping is a methodof quoting single characters. The escape() preceding a character tells the shell tointerpret that character literally.

With certain commands and utilities, such as echo and sed, escaping a character may have theopposite effect - it can toggle on a special meaning for thatcharacter.

Special meanings of certainescaped characters

used with echo andsed

means newline

means return

means tab

v

means vertical tab



means backspace

a

means alert (beep or flash)

xx

translates to the octal ASCII equivalent of 0nn, where nn is a string of digits

The $' ... ' quoted string-expansion construct is a mechanism that uses escaped octal or hex values to assign ASCII characters to variables, e.g., quote=$'42'.

Example 5-2. Escaped Characters

#!/bin/bash# escaped.sh: escaped characters################################################################ First, let's show some basic escaped-character usage. ################################################################# Escaping a newline.# ------------------echo "" echo "This will printas two lines." # This will print# as two lines.echo "This will print as one line." # This will print as one line.echo; echoecho "=============" echo "vvvv"  # Prints vvvv literally.# Use the -e option with 'echo' to print escaped characters.echo "=============" echo "VERTICAL TABS" echo -e "vvvv"   # Prints 4 vertical tabs.echo "==============" echo "QUOTATION MARK" echo -e "42"   # Prints " (quote, octal ASCII character 42).echo "==============" # The $'X' construct makes the -e option unnecessary.echo; echo "NEWLINE and (maybe) BEEP" echo $''   # Newline.echo $'a'   # Alert (beep). # May only flash, not beep, depending on terminal.# We have seen $'nn" string expansion, and now . . .# =================================================================== ## Version 2 of Bash introduced the $'nn' string expansion construct.# =================================================================== #echo "Introducing the $' ... ' string-expansion construct . . . " echo ". . . featuring more quotation marks." echo $' 42 '   # Quote (") framed by tabs.# Note that  'nn' is an octal value.# It also works with hexadecimal values, in an $'xhhh' construct.echo $' x22 '  # Quote (") framed by tabs.# Thank you, Greg Keraunen, for pointing this out.# Earlier Bash versions allowed 'x022'.echo# Assigning ASCII characters to a variable.# ----------------------------------------quote=$'42' # " assigned to a variable.echo "$quote Quoted string $quote and this lies outside the quotes." echo# Concatenating ASCII chars in a variable.triple_underline=$'137137137'  # 137 is octal ASCII code for '_'.echo "$triple_underline UNDERLINE $triple_underline" echoABC=$'10110210310'   # 101, 102, 103 are octal A, B, C.echo $ABCechoescape=$'33' # 033 is octal for escape.echo ""escape" echoes as $escape" #   no visible output.echoexit 0

A more elaborate example:

Example 5-3. Detecting key-presses

#!/bin/bash# Author: Sigurd Solaas, 20 Apr 2011# Used in ABS Guide with permission.# Requires version 4.2+ of Bash.key="no value yet" while true; do  clear  echo "Bash Extra Keys Demo. Keys to try:"   echo  echo "* Insert, Delete, Home, End, Page_Up and Page_Down"   echo "* The four arrow keys"   echo "* Tab, enter, escape, and space key"   echo "* The letter and number keys, etc."   echo  echo " d = show date/time"   echo " q = quit"   echo "================================"   echo # Convert the separate home-key to home-key_num_7: if [ "$key" = $'x1bx4fx48' ]; then  key=$'x1bx5bx31x7e'  #   Quoted string-expansion construct.  fi # Convert the separate end-key to end-key_num_1. if [ "$key" = $'x1bx4fx46' ]; then  key=$'x1bx5bx34x7e' fi case "$key" in  $'x1bx5bx32x7e')  # Insert   echo Insert Key  ;  $'x1bx5bx33x7e')  # Delete   echo Delete Key  ;  $'x1bx5bx31x7e')  # Home_key_num_7   echo Home Key  ;  $'x1bx5bx34x7e')  # End_key_num_1   echo End Key  ;  $'x1bx5bx35x7e')  # Page_Up   echo Page_Up  ;  $'x1bx5bx36x7e')  # Page_Down   echo Page_Down  ;  $'x1bx5bx41')  # Up_arrow   echo Up arrow  ;  $'x1bx5bx42')  # Down_arrow   echo Down arrow  ;  $'x1bx5bx43')  # Right_arrow   echo Right arrow  ;  $'x1bx5bx44')  # Left_arrow   echo Left arrow  ;  $'x09')  # Tab   echo Tab Key  ;  $'x0a')  # Enter   echo Enter Key  ;  $'x1b')  # Escape   echo Escape Key  ;  $'x20')  # Space   echo Space Key  ;  d)   date  ;  q)  echo Time to quit...  echo  exit 0  ;  *)   echo You pressed: '"$key"'  ; esac echo echo "================================"  unset K1 K2 K3 read -s -N1 -p "Press a key: "  K1="$REPLY"  read -s -N2 -t 0.001 K2="$REPLY"  read -s -N1 -t 0.001 K3="$REPLY"  key="$K1$K2$K3" doneexit $?

See also Example 37-1.

"

gives the quote its literal meaning

echo "Hello" # Helloecho ""Hello" ... he said." # "Hello" ... he said.

$

gives the dollar sign its literal meaning (variable name following $ will not be referenced)

echo "$variable01"   # $variable01echo "The book cost $7.98."  # The book cost $7.98.

gives the backslash its literal meaning

echo ""  # Results in # Whereas . . .echo ""   # Invokes secondary prompt from the command-line.   # In a script, gives an error message.# However . . .echo ''   # Results in 

The behavior of depends on whetherit is escaped, strong-quoted,weak-quoted, or appearing withincommand substitution or ahere document.

  #  Simple escaping and quotingecho z   #  zecho z  # zecho 'z' # zecho 'z' # zecho "z" # zecho "z" # z  #  Command substitutionecho `echo z` #  zecho `echo z`   #  zecho `echo z`  # zecho `echo z` # zecho `echo z`   # zecho `echo z`  # zecho `echo "z"`  # zecho `echo "z"` # z  # Here documentcat <<EOF  z  EOF   # zcat <<EOF  z EOF   # z# These examples supplied by St�phane Chazelas.

Elements of a string assigned to a variable may be escaped, but the escape character alone may not be assigned to a variable.

variable=echo "$variable" # Will not work - gives an error message:# test.sh: : command not found# A "naked" escape cannot safely be assigned to a variable.##  What actually happens here is that the "" escapes the newline and#+ the effect is variable=echo "$variable" #+  invalid variable assignmentvariable=23skidooecho "$variable" #  23skidoo #  This works, since the second line #+ is a valid variable assignment.variable= # ^ escape followed by spaceecho "$variable" # spacevariable=echo "$variable" # variable=echo "$variable" # Will not work - gives an error message:# test.sh: : command not found##  First escape escapes second one, but the third one is left "naked",#+ with same result as first instance, above.variable=echo "$variable" # # Second and fourth escapes escaped. # This is o.k.

Escaping a space can prevent word splitting in a command's argument list.

file_list="/bin/cat /bin/gzip /bin/more /usr/bin/less /usr/bin/emacs-20.7" # List of files as argument(s) to a command.# Add two files to the list, and list all.ls -l /usr/X11R6/bin/xsetroot /sbin/dump $file_listecho "-------------------------------------------------------------------------" # What happens if we escape a couple of spaces?ls -l /usr/X11R6/bin/xsetroot /sbin/dump $file_list# Error: the first three files concatenated into a single argument to 'ls -l'# because the two escaped spaces prevent argument (word) splitting.

The escape also provides a means of writing amulti-line command. Normally, each separate line constitutesa different command, but an escape at the endof a line escapes the newline character,and the command sequence continues on to the next line.

(cd /source/directory && tar cf - . ) | (cd /dest/directory && tar xpvf -)# Repeating Alan Cox's directory tree copy command,# but split into two lines for increased legibility.# As an alternative:tar cf - -C /source/directory . |tar xpvf - -C /dest/directory# See note below.# (Thanks, St�phane Chazelas.)

If a script line ends with a |, a pipe character, then a , an escape, is not strictly necessary. It is, however, good programming practice to always escape the end of a line of code that continues to the following line.

echo "foobar" #foo#barechoecho 'foobar' # No difference yet.#foo#barechoecho foobar # Newline escaped.#foobarechoecho "foobar" # Same here, as  still interpreted as escape within weak quotes.#foobarechoecho 'foobar' # Escape character  taken literally because of strong quoting.#foo#bar# Examples suggested by St�phane Chazelas.


Copyright © 2000, by Mendel Cooper <[email protected]>
(Sebelumnya) 4. Introduction to Variables a ...6. Exit and Exit Status (Berikutnya)