declare -a a # 创建一个数值 arr=("1" "2" "abc" "4" 5) # 数组赋值 arr[0]=8 # 数组赋值 # 以下是*和@输出的区别,*是扩展成一串,而@分开了 for i in "${arr[*]}"; do echo $i; done 8 2 abc 4 5 for i in "${arr[@]}"; do echo $i; done 8 2 abc 4 5
string=20 if [ -z string ]; then # 判断字符串是否为空 echo "string is empty" elif [[ $string =~ ^h.+o$ ]]; then # 匹配正则表达式 echo "string is right" elif (( string>10 )); then # 数值比较 echo "string is greater than 10" else echo "string is not be matched" fi # 输出"string is greater than 10"
case分支
1 2 3 4 5 6 7 8 9 10 11
case $i in "1") echo "input is 1" ;; "2") echo "input is 2" ;; *) echo "input is $i" ;; esac
#!/bin/bash -x # a quicksort algorithm implement in shell
arr=(3 23 4 1 45 56 34 78 79 89)
get_pos() { local low=$1 local high=$2 local value=${arr[$low]} # 数组取值
while (( $low<$high )); do while (( $low<$high && $value<=${arr[$high]} )); do high=$(($high-1)) done if (( $low<$high )); then arr[$low]=${arr[$high]} ((++low)) # 整数运算只能在(())中 fi while (( $low<$high && $value>=${arr[$low]} )); do low=$(($low+1)) done if (( $low<$high )); then arr[$high]=${arr[$low]} ((--high)) # 整数运算只能在(())中 fi done
arr[$low]=$value return $low }
quicksort() { local low=$1 local high=$2 local pos=0 local tempLow=0 local tempHigh=0 if (( $low<$high )); then get_pos $low $high pos=$? # 获得返回值 tempLow=$(($pos-1)) tempHigh=$(($pos+1)) quicksort $low $tempLow quicksort $tempHigh $high fi }