martes, 15 de enero de 2013

Understanding Bash quoting

We use this simple bash file to validate all examples

#!/bin/bash
echo "Arguments count : $#"
echo "All : $@"

for (( i=0; i<=$#; i++ )); do
    eval arg=\${$i}
    echo $i : $arg
done

exit

Especial character # use to comment a line. See next.

./print-arg.sh arg1 arg2 arg3  #arg4 ignore 
Arguments count = 3
All : arg1 arg2 arg3
0 : arg1
1 : arg2
2 : arg3

To avoid bash interprets the character # we use quotes, simple or double do not matter

./print-arg.sh arg1 arg2 arg3  '#arg4' ignore 
Arguments count = 5
All : arg1 arg2 arg3 #arg4 ignore
0 : arg1
1 : arg2
2 : arg3
3 : #arg4
4 : ignore
./print-arg.sh arg1 arg2 arg3   "#arg4" ignore 
Arguments count = 5
All : arg1 arg2 arg3 #arg4 ignore
0 : arg1
1 : arg2
2 : arg3
3 : #arg4
4 : ignore

Bash interprets the blank space has argument separation, to avoid this we use simple or double quoted

./print-arg.sh "arg1 arg2" arg3    "#arg4 ignore" 
Arguments count : 3
All : arg1 arg2 arg3 #arg4 ignore
0 : ./print-arg.sh
1 : arg1 arg2
2 : arg3
3 : #arg4 ignore

To pass espaces use simple or double quoting, to pass quote as another character, use simple to double and double to simple. Use double if there is some spaces and use escape char \ to pass double quote bettewn them.
Some special chars in bash

  • * : use for expand files in current path
  • space : Use for arguments and elements separation
  • # : from this character to the end of the line text is a comment
  • $ : for variables or parameters sustitution
  • ; : end of command, another can start from here, new line is not necessary
  • ! : show execute command from history number
  • \ : wrap line at the end, the command continues in the next line, like a continuos line,
  • \ : cancel or scape the meaning of next character, ($,\,',",!,#,space,*) making this part of string ("\" - need another " to enclose)
  • ' : enclose text to avoid interprets of next characters ($,",\,#,space,;,",!,*)
  • " : enclose text to avoid interprets of characters (',;,#,\,space,) - (\") can not avoided
  • ",' : another character than space near of close quote is part of string ( " "abcd - is one string with spaces a begining)

Tips:
You can get enclose twice at the same string if close and open quote are near one to another. ('\') is \ enclosed, (' 'abcd) is an enclose espace plus letters, (' ''abcd') is the same, two enclosed together. ('\'') another ' needed to finish the second enclosure.
(\") enclosed betwen double quote is like an " Ej ("\"") ("\"""abcd" - two enclosed string near appear as one string.).

./print-arg.sh "ab'cd" 'ab"cd' 'ab''cd' "ab""cd" !645 "$HOME \$HOME \" !645 \!" '\" \$ $HOME !645'  
Arguments count : 7
All : ab'cd ab"cd abcd abcd ll /home/main $HOME " ll \! \" \$ $HOME !645 \# \# ab\ cd
0 -./print-arg.sh-
1 -ab'cd-
2 -ab"cd-
3 -abcd-
4 -abcd-
5 -ll-
6 -/home/main $HOME " ll \!-
7 -\" \$ $HOME !645-
8 -#-
9 -ab cd-

No hay comentarios:

Publicar un comentario