基础 Basics
变量
变量赋值时 需要注意等号两端无需空格。varName=value
Value assignment is done using the “=” sign. Note that no space permitted on either side of = sign when initializing variables.
varName = value
不等于 varName=value
。前者表示等量关系测试,后者表示赋值操作。
使用变量时,可以这样写 echo ${var}
变量也可以使用某个命令的输出
FILELIST=`ls`
# or FILELIST=$(ls)
FileWithTimeStamp=/tmp/my-dir/file_$(/bin/date +%Y-%m-%d).txt
变量的运算需要再如下表达式$((expression))
中实现
A=3
B=$((100 * $A + 5))
查看字符串的长度
#!/bin/bash
STRING="This is a string"
echo ${#STRING} #16
字符串子串提取
STRING="this is a string"
POS=1
LEN=3
echo ${STRING:$POS:$LEN} # his
数组
# basic construct
# array=(value1 value2 ... valueN)
array=(23 45 34 1 2 3)
#To refer to a particular value (e.g. : to refer 3rd value)
echo ${array[2]}
#To refer to all the array values
echo ${array[@]}
#To evaluate the number of elements in an array
echo ${#array[@]
使用shell进行数学运算
shell 使用let
、(())
、[]
执行整数的基本运算。
运算示例:
#!/bin/bash
num1=4
num2=5
let result=num1+num2
echo $result
let num1++
let num2--
let result=num1+num2
echo $result
echo $num1
echo $num2
let num1+=6
let num2-=6
result=$[ num1 + num2 ]
result=$[ $num1 + 5]
result=$(( num1 + 50 ))
result=`expr 4 + 4 `
result=$(expr $num1 + 5)
文件描述符与重定向
cmd 2>&1 alloutput.txt
#equal
cmd &> alloutput.txt
子shell的利用
使用()操作符来定义一个子shell
(cd /bin;ls)
流程 与 循环
if else
if [ expression ]; then
else
fi
"$a" = "$b" $a is the same as $b
#note1: whitespace around = is required
#note2: use "" around string variables to avoid shell expansion of special characters as *
比较和测试
[ condition ] && action
[ condition ] || action
[ $var -eq 0] or [ $var1 -eq 0 ]
[ $var -gt 0 ] and [ $var -lt 0 ]
[ $var1 -ne 0 -a $var2 -gt 2 ]
#测试字符串是否相同
[ [$str1 = $srt2 ]]
[[ $str1 == $str2 ]]
[[ -z $str1 ]] #如果str1为空串,则为真
[[ -n $str1 ]] #如果str2不为空串,则返回真;
case
case "$variable" in
"$condition1")
;;
"$conditon2")
;;
esac
for
for arg in [list]
do
commands
done
# loop on array member
NAMES=(Joe Jenny Sara Tony)
for N in ${NAMES[@]} ; do
echo "My name is $N"
done
# loop on command output results
for f in $( ls prog.sh /etc/localtime ) ; do
echo "File is: $f"
done
# loop1
for i in {1..6}
do
echo $i
done
# loop2
for i in `seq 0 6`
do
echo $i
done
使用{start..end}
比 seq start end
命令略快。
while
while [condition]
do
commands
done
COUNT=4
while [ $COUNT -gt 0 ]; do
echo "Value of count is: $COUNT"
COUNT=$(($COUNT - 1))
done