Quoting and Escaping in Linux

Quoting


Quoting is used in Linux to protect or limit the substitution of special character and for grouping of words.

Example

[ved@localhost ~]$  echo $PATH
-bash: /usr/kerberos/bin:/usr/bin:/bin:/usr/sbin:/sbin:

[ved@localhost ~]$ echo ‘$PATH’
$PATH

Here when we are using single quote, we protect the literal meaning of $.



Quoting are three types

  1. Double quote
  2. Single Quote
  3. Escape character


Double Quote


It also called weak quoting.  Double quote prevent all special character (meta-characters like "*" or "?) meaning except command substitution like $, back tilt (`) and escape ( \ ) character. 

Example


[ved@localhost ~]$ echo "Hi"
Hi
[ved@localhost ~]$ echo "\"Hi\""
“Hi”
[ved@localhost ~]$ var=40
[ved@localhost ~]$ echo $var
40
[ved@localhost ~]$ echo "$var"
40
[ved@localhost ~]$ echo "\$var"
$var


Double quote prevents whitespaces as separation of words. A group of words enclosed in double quotes represents itself as a single word.



[ved@localhost ~]$  var=”Welcome to Page Linux”
[ved@localhost ~]$ cat quote.sh
for a in “$Var”
do
echo "$a"
done


[ved@localhost ~]$ ./quote.sh
Welcome to Page Linux
[ved@localhost ~]$ cat quotes.sh
for a in $Var
do
echo "$a"
done

[ved@localhost ~]$ ./quotes.sh
Welcome
to
Page
Linux





Single Quote


It is also called strong quoting because all special character meaning is turned off in single quote.


[ved@localhost ~]$ echo '$var'
$var
[ved@localhost ~]$ echo '\$var'
\$var


                            

But we can’t use the single quote in between single quote.

Example

[ved@localhost ~]$ echo ‘ Ved’s Page’ 
       
It can’t work, write it as

[ved@localhost ~]$ echo ‘ Ved’\’’s Page’




Escape


Escaping is used for quoting a single characters, as explained below in example.


[ved@localhost ~]$ variable=\\
[ved@localhost ~]$ echo "$variable"
\
[ved@localhost ~]$ variable=\\\
[ved@localhost ~]$ echo "$variable"
error
[ved@localhost ~]$ variable=\\\\
[ved@localhost ~]$ echo "$variable"
\\




Some Escape Character have special meaning as below.


\n         means newline
\r          means return
\t          means tab
\v         means vertical tab
\b         means backspace
\a          means alert (beep or flash)
\0xx      translates to the octal ASCII equivalent


-e option

Use the -e option with echo to print these escaped characters.

Example

$ echo “Hello \t World”
hello \t world
$ echo -e "hello \t world"
hello    world



Escaping character can also be used for newline escaping.

[ved@localhost ~]$ echo "This is first line
>this is second line"

This is first line
this is second line

[ved@localhost ~]$ echo "This is first line \
>this is second line"


This is first line this is second line

[ved@localhost ~]$ echo ‘This is first line \
>this is second line’

This is first line \
this is second line





No comments: