Pages

Monday, 12 January 2015

Bash Variable Expansion

Shell Parameter and Variable Expansion

The "$" character introduces parameter expansion, command substitution, or arithmetic expansion.

e.g
[root@localhost ~]# echo $SHELL
/bin/bash
[root@localhost ~]# echo ${SHELL}
/bin/bash

The basic form of parameter expansion is "${PARAMETER}". The value of "PARAMETER" is substituted. The braces are required when "PARAMETER" is a positional parameter with more than one digit, or when "PARAMETER" is followed by a character that is not to be interpreted as part of its name.

Length of Variable

[root@localhost ~]# echo $SHELL
/bin/bash

[root@localhost ~]# echo ${#SHELL}
9
[root@localhost ~]# declare -i a=123
[root@localhost ~]# declare -p a
declare -i a="123"
[root@localhost ~]# echo ${#a}
3

Indirect Expansion

If the first character of "PARAMETER" is an exclamation point, Bash uses the value of the variable formed from the rest of "PARAMETER" as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of "PARAMETER" itself. This is known as indirect expansion.

[root@localhost ~]# echo ${!SH*}
SHELL SHELLOPTS SHLVL

Command Substitution

$(COMMAND) or `COMMAND`

[root@localhost ~]# date
Thu Jan  8 17:01:43 PST 2015
[root@localhost ~]# echo date
date
[root@localhost ~]# echo `date`
Thu Jan 8 17:01:51 PST 2015
[root@localhost ~]# echo This is the date: `date`
This is the date: Thu Jan 8 17:01:56 PST 2015

Arithmetic Expansion

BASH only supports interger arithmetic
[root@localhost ~]# product=$((3.6*4.9))
-bash: 3.6*4.9: syntax error: invalid arithmetic operator (error token is ".6*4.9")
Interpret as command expansion
[root@localhost ~]# product=$("36*49")
-bash: 36*49: command not found
[root@localhost ~]# product=$(36*49)
-bash: 36*49: command not found
[root@localhost ~]# product=$((36*49))
[root@localhost ~]# echo $product
1764


[root@localhost ~]# expr 4 + 5
9
[root@localhost ~]# a=$(expr 4 + 5)
[root@localhost ~]# echo $a
9

Arithmetic for decimal number

- bc
[root@localhost ~]# echo "scale=100;3.222553*8.77777" | bc
28.28682904681
[root@localhost ~]# echo "3.222553*8.77777" | bc
28.286829
[root@localhost ~]# echo "scale=2;3/8" | bc
.37
[root@localhost ~]# echo "scale=5;3/8" | bc
.37500
[root@localhost ~]# echo "scale=1;3/8" | bc
.3
[root@localhost ~]# echo "scale=2;3/8" | bc
.37
[root@localhost ~]# echo "3/8" | bc
0

No comments:

Post a Comment