Example:
$ cat >question_ex.sh
var1=10
(( var2 = var1<20?0:100 ))
echo $var2
$ sh question_ex.sh
0
The command performing test operation by (( var2 = var1<20?0:100 ))
is same as,
# if [ "$var1" -lt 20 ]
# then
# var2=0
# else
# var2=100
# fi
- In a parameter substitution expression, the question mark (?) tests whether a variable has been set.
If we use following syntax,
${parameter?err_msg}, ${parameter:?err_msg}
then if parameter is set, then it's value is used, else it prints err_msg.
$ echo ${var?The variable is not set}
bash: var: The variable is not set
$ echo ${USER?The variable is not set}
Arju
In the above example in first case variable var is not set, hence error message appeared while in the second case variable USER is set and hence displays it's value.
- In case of pattern matching question mark (?) matches the preceding pattern element zero or one time. For example if we write xy?z then it matches only xz and xyz which is described in http://arjudba.blogspot.com/2009/07/list-of-metacharacters-in-regular.html. Note that with "?" filename expansion in globbing does not behave exactly like regular expression while in case of utility like sed/awk it behaves like regular expression.
No comments:
Post a Comment