Linux - Bash Shell Scripting - Expressions and Substrings
Expressions
Sometimes in a script, you would like to evaluate an expression. For example, to find the sum of two variables. The expr command can be used to do this,
$ cat testsum.sh
#!/bin/bash
v1=12
v2=39
v3=`expr $v1 + $v2`
echo $v3
$ ./testsum.sh
51
Note that the expr command must be enclosed in backquotes `…` for this to properly work. Typing ‘man expr’ will display a help screen about the expr command.
Substrings
The expr substr command can be used to extract a substring from a string variable, e.g., this program prints the individual characters of a string stored in a variable v,
v="foobar"
len=`expr length $v`
for i in `seq 1 1 $len`; do
echo -n `expr substr $v $i 1`
done
echo
The syntax of expr substr is, 'expr substr string pos len' which will extract len characters from the string string starting at position pos. Note that the first character of the string string is at position 1.
Previous - For and While Loops
No comments:
Post a Comment