Friday, October 2, 2009

Single quote, double quote and comma in shell script

- Single quotes are called the full quoting mechanism. Anything you write within single quote it preserves all special characters within single quote. So within single quote it does not do any variable substitution.
Example of single quote:

$ cat >single_quote.sh
echo 'Process ID variable is defined by $$'
echo 'Exit status is defined by $?'

$ sh single_quote.sh
Process ID variable is defined by $$
Exit status is defined by $?

Here the special characters are preserved as they are written inside single quote.

- Double quotes are called partial quoting mechanism. Anything you write within double quote it interprets most of the special characters within double quote.
Example of double quote:

$ cat >double_quote.sh

echo "Process ID variable is defined by $$"
echo "Exit status is defined by $?"

$ sh double_quote.sh
Process ID variable is defined by 5256
Exit status is defined by 0

Note that $$ and $? is interpreted.

- Comma(,) operator chains together two or more arithmetic operations. All the operations are evaluated but only the last one is returned.
Example:

let "t1 = ((a = 9, 3 + 2, 2 - 1, 15 - 4))"
echo "t1 = $t1" # t1 = 11
# Here t1 is set to the result of the last operation that is 11. variable a=9

let "t2 = ((a = 9, 15 / 3))" # Set "a" and calculate "t2".
echo "t2 = $t2 a = $a" # t2 = 5 a = 9

- In case of parameter substitution single comma is used to make first character as lowercase and double comma is used to make all characters are lowercase.

Example:

$ cat >lower_upper.sh
var=mixEdCasecharacteR
echo ${var}
echo ${var,}
# * First char --> lowercase.
echo ${var,,}
# ** All chars --> lowercase.
echo ${var^}
# * First char --> uppercase.
echo ${var^^}
# ** All chars --> uppercase.

Note that above example is application only for on and after of version 4 of Bash.
Related Documents

No comments:

Post a Comment