shell 基本操做小結

1.echoif else fi命令

#!/bin/bash
echo hello;echo there
filename=demo.sh
if [ -e "$filename" ]; then 
    echo "$filename already exists!";cp $filename $filename.bak
else
    echo "$filename does not exist!";
fi;
echo "File test complete!"

運行結果(demo.sh不存在):html

hello
there
demo.sh does not exist!
File test complete!

須要注意的是filename=demo.sh等號兩邊是不能有空格的;if [ -e "$filename" ]中[]左右兩側都是有空格的。java

2.shell基本操做

2.1 變量大於,等於,小於

#!/bin/bash
a=1
if [ $a -gt 0 ]; then
    echo "greater than zero!"
else
    echo "no more than zero!"
fi
if [[ $a -lt 0 ]]; then
    echo "less than zero!"
else
    echo "no less than zero!"
fi
if [[ a -eq 1 ]]; then
    echo "equal to 1!"
else
    echo "not equal to 1!"
fi

-gt表示大於;-lt表示小於;-eq表示等於。運行結果爲:linux

greater than zero!
no less than zero!
equal to 1!

2.2 三目運算符(?:)

# ? is 3 operator
b=10
((t=b<20?6:4)) # t = 6
echo "t=$t"
# variable in () is a part region variable
(b=20;echo "b = $b") # b = 20
echo "b = $b" # b = 10

和C,java等語言相似,shell中的?:也是三目運算符。()表示一個創建局部做用域,能夠暫時屏蔽全局變量。上式的運行結果爲:git

t=6
b = 20
b = 10

2.3 數組

2.3.1 數組建立
# () create an array
arr=(1 2 3 5 6)
echo "arr[3] = ${arr[3]}"

輸出:正則表達式

arr[3] = 5
2.3.2 數組長度
# get the length of array
echo "length of arr is ${#arr[*]}" # 5
echo "length of arr is ${#arr[@]}" # 5

輸出:shell

length of arr is 5
length of arr is 5
2.3.3 輸出數組元素
# get all content of array
echo "arr:${arr[*]}" # 1 2 3 5 6
# or
echo "arr:${arr[@]}" # 1 2 3 5 6

輸出:編程

arr:1 2 3 5 6
arr:1 2 3 5 6
2.3.4 修改數組元素
# assign a new element to an array
arr[1]=100
echo "arr:${arr[@]}" # 1 100 3 5 6
# if assign index if out of bound,then auto create a new element of array
arr[10]=20 # 1 100 3 5 6 20
echo "arr:${arr[@]}"

輸出:數組

arr:1 100 3 5 6
arr:1 100 3 5 6 20

注意若是賦值索引超出數組長度,至關因而給數組末尾增長一個新元素。bash

2.3.5 刪除數組元素
# delete the element of array
unset arr[1] # delete the arr[1],1 3 5 6 20
echo "arr:${arr[*]}" # 1 3 5 6 20
# clear the whole array
unset arr 
echo "${#arr[@]}" # length 0

輸出:less

arr:1 3 5 6 20
0

unset 若是跟上數組的索引,是刪除該位置的數組元素;若是直接跟數組名,至關因而清空數組。

2.3.6 數組切片
arr=(1 2 4 10)
# slice of array
# ${array_name[*]:start:length},return is a string
echo "${arr[@]:0:3}" # 1 2 4
# assignment
arr1=(${arr[*]:1:2}) # arr1:2 4
echo "${#arr1[@]}"
echo "arr1:${arr1[@]}"

輸出:

1 2 4
2
arr1:2 4
2.3.7 數組元素替換
# replace
# ${array_name[@]/origin_element/new_element}
# this operation doesn't change the origin array
# and will return a string that seperated by space
echo "${arr1[*]/2/20}" # 20 4,arr1:2 4
arr1=(${arr1[*]/4/40}) # arr1:2 40
echo "${arr1[*]}" # 2 40

輸出:

20 4
2 40

2.4 文件操做

# file operation
if [ ! -w 't.txt' ]; then
    touch t.txt
fi
echo 'test text' > t.txt 
cp t.{txt,back} # cp t.txt to t.back
filename="/home/lyrichu/login"
if [ -r $filename ] # if file is readable
    then 
    echo "$filename is readable!"
else
    echo "$filename is not readable!"
fi

if [ -e $filename ]
    then
    echo "$filename exists!"
else
    echo "$filename doesn't exist!"
fi

輸出:

/home/lyrichu/login is not readable!
/home/lyrichu/login doesn't exist!

上面的代碼首先檢查t.txt文件是否可寫,若是不可寫,則從新建立一個文件;而後向t.txt文件寫入字符串'test text';接着複製t.txt文件到t.back文件;
而後判斷/home/lyrichu/login文件是否可讀以及是否存在。

2.5 {}建立一個代碼塊

# {} create a code block
a=10;echo "a=$a"
{ a=20; } # a = 20
echo "a=$a" # a = 20

輸出:

a=10
a=20

2.6 expr 計算表達式的值

val=`expr $a + $b` # a = 20,b = 10
echo "a + b = $val" # a + b = 30

val=`expr $a \* $b` # \* means multiply,a*b = 10*20 = 200
echo "a*b=$val"

# divide
val=`expr $a / $b` # 20/10 = 2
echo "a / b = $val"

# mod
val=`expr $a % 9` # 20 % 9 = 2
echo "$a % 9 = $val" # 20 % 9 = 2

輸出:

a + b = 30
a*b=200
a / b = 2
20 % 9 = 2

expr能夠計算shell表達式的值,上式分別計算了+,*,/,%運算,注意乘法須要使用\*轉義。

2.7 邏輯運算符

if [ $a == $b ]
then echo "a == b!"
fi
if [ $a != $b ] 
    then 
    echo "a != b" 
fi 

# && logit and
if [[ $a -gt 10 && $b -lt 20 ]]
    then
    echo "$a > 10 and $b < 20!"
else
    echo "bad condition!"
fi
# || logit or 
if [[ $a -gt 15 || $b -gt 15 ]]
    then
    echo "a > 15 or b > 15"
else
    echo "a<=15 and b<=15"
fi

輸出:

a != b
20 > 10 and 10 < 20!
a > 15 or b > 15

== 用於比較數字相等;!=用於比較數字不等。&&表示shell中的邏輯與;||表示shell中的邏輯或運算。

2.8 字符串操做

#!/bin/bash
s1="abhsgd"
# 獲取字符串長度
echo "length of s1:" ${#s1}
#提取子字符串
# ${string:position},在string中,從position位置開始提取子字符串
echo ${s1:2} # hsgd
# ${string:position:length},string中,從position位置開始提取長度爲length的子字符串
echo ${s1:2:2} # hs 
# ${string#substring},從string的開頭, 刪除最短匹配substring的子串,返回刪除子串以後的字符串
echo ${s1#ab} #hsgd
# ${string##substring},從string的開頭, 刪除最長匹配substring的子串
echo ${s1##abh} # sgd
# ${string%substring},從string的結尾, 刪除最短匹配substring的子串
echo ${s1%gd} # absh
# ${string%%substring},從string的結尾, 刪除最長匹配substring的子串
echo ${s1%%hsgd} # ab
# ${string/substring/replacement},使用replacement,來代替第一個匹配的substring
echo ${s1/hs/HS} # abHSgd
# ${string//substring/replacement},使用replacement, 代替全部匹配的substring
s2=ahjhjhhshdg
echo ${s2//h/H} # aHjHjHHsHdg
# ${string/#substring/replacement},若是string的前綴匹配substring, 那麼就用replacement來代替匹配到的substring
echo ${s2/#ahj/AHJ} # AHJhjhhshdg
# ${string/%substring/replacement},若是string的後綴匹配substring, 那麼就用replacement來代替匹配到的substring
echo ${s2/%shdg/SHDG} # ahjhjhhSHDG
## 注:上面replacement能夠是正則表達式,好比:
s3=/home/lyrichu/demo.txt 
# 獲得文件名
echo ${s3##*/} #demo.txt 
# 獲得目錄名
echo ${s3%/*} # /home/lyrichu

輸出:

length of s1: 6
hsgd
hs
hsgd
sgd
abhs
ab
abHSgd
aHjHjHHsHdg
AHJhjhhshdg
ahjhjhhSHDG
demo.txt
/home/lyrichu

2.9 控制流

2.9.1 if語句
a=10
b=20
if [ $a == $b ]
    then
    echo "$a == $b !"
elif [[ $a -gt $b ]]; then
    echo "$a > $b!"
elif [[ $a -lt $b ]]; then
    echo "$a < $b!"
else
    echo "Error!"
fi

# test command
if test $a -lt $b
    then 
    echo "$a < $b!"
else
    echo "$a >= $b!"
fi

輸出:

10 < 20!
10 < 20!

其中test命令用來判斷一條語句的真假。

2.9.2 for 語句
# for loop
for i in 1 2 3 4
do
    echo "The value is $i"
done

# for loop of string
for s in This is a string
do
    echo "$s"
done

輸出:

The value is 1
The value is 2
The value is 3
The value is 4
This
is
a
string
2.9.3 while 循環
#while loop
i=1
while(( $i<5 ))
do
    echo "$i"
    let "i++"
done

echo "Press CTRL+D to exit!"
echo -n "Who is the most beautiful girl?"
while read MAN
do
    echo "Yes! $MAN is really beautiful!"
done

輸出:

1
2
3
4
Press CTRL+D to exit!
Who is the most beautiful girl?yp
Yes! yp is really beautiful!
2.9.4 case 語句
# case mode
echo "Please input a number between 1 to 4!"
read input
case input in
    1) echo "Your choice is 1!"
    ;;
    2) echo "Your choice is 2!"
    ;;
    3) echo "Your choice is 3!"
    ;;
    4) echo "Your choice is 4!"
    ;;
    *) echo "You don't choose a number between 1 and 4!"
    ;;
esac 

## break 
while :
do
    echo "PLease input a number between 1 and 5!"
    read n 
    case $n in 
        1|2|3|4|5) echo "Your input number is $n!"
        ;;
        *) echo "Your input is not between 1 and 5!"
            break
        ;;
    esac 
done

輸出:

Please input a number between 1 to 4!
3
Your choice is 3!
PLease input a number between 1 and 5!
5
Your input number is 5!
PLease input a number between 1 and 5!
10
Your input is not between 1 and 5!

2.10 函數

2.10.1 一個簡單的沒有參數,沒有返回值的函數
func1(){ # fuction that does not have parameters
    echo "This is my first function!"
}
# call function
func1

輸出:

This is my first function!
2.10.2 帶有返回值的函數
func2(){ # function with return
    echo "This is function that has return!"
    return 1
}
# use $? to get the function return value
func2
echo "The return value of func2 is $?"

輸出:

This is function that has return!
The return value of func2 is 1

在末尾使用return關鍵字便可以返回一個值,使用$?來獲取函數的返回值。

函數傳遞參數,獲取參數總數,參數值以及第i個參數
# input parameters of function
# $1,$2,... to the first n parameter
func3(){
    n=$# # get the total number of parameters
    echo "There are total $n parameters of func3!"
    echo "The first parameter is:$1"
    echo "The second parameter is $2"
    echo "The tenth parameter is ${10}"
    echo "The all parameters as string is:$*"
}
func3 1 2 3 4 5 6 7 8 9 10 11 12

輸出:

There are total 12 parameters of func3!
The first parameter is:1
The second parameter is 2
The tenth parameter is 10
The all parameters as string is:1 2 3 4 5 6 7 8 9 10 11 12

3.一些簡單的shell 實例

3.1 計算3個數的最大值

# calculate the max value of 8,4,5
a=5
b=4
c=8
i=$a

if [[ $i -lt $b ]]
    then
    i=$b
fi

if [[ $i -lt $c ]]
    then
    i=$c
fi
echo "The max value of $a,$b,$c is $i"

輸出:

The max value of 5,4,8 is 8

3.2 隨機猜數

#!/bin/bash
# random generate a number between 1 and 3, and let you to
# guess the number's value,if you are right,then echo "You guess right!"
# else echo "You guess wrong!"
# use while to play the game,input "quit" to quit the game
# $RANDOM generate a number between 0 and 32767
while :
do
    r=$RANDOM
    r=`expr $r % 3 + 1` # between 1 and 3
    echo "Please input a number between 1 and 10(enter quit to quit the game):"
    read g
    if [[ $g = "quit" ]]
        then
        break
    elif [[ $g == $r ]]; then
        echo "You guess right!"
    else
        echo "You guess wrong!"
    fi
done

輸出:

Please input a number between 1 and 10(enter quit to quit the game):
2
You guess right!
Please input a number between 1 and 10(enter quit to quit the game):
3
You guess right!
Please input a number between 1 and 10(enter quit to quit the game):
3
You guess wrong!
Please input a number between 1 and 10(enter quit to quit the game):
quit

3.3 求小於100的全部偶數的和

#!/bin/bash
# sum the even number that less than 100
i=2
s=0
while [[ $i -lt 100 ]]; do
    s=`expr $s + $i`
    i=`expr $i + 2`
done
echo "The even number that less than 100's sum is $s"

輸出:

The even number that less than 100's sum is 2450

3.4 輸出星號(*)金字塔

#!/bin/bash
# output the pyramid of stars
for i in 4 3 2 1 0
do
    j=$i 
    while [[ $j -gt 0 ]]
    do
        echo -n " "
        let "j--"
    done
    j=`expr 9 - 2 \* $i`
    while [[ $j -gt 0 ]]
    do
        echo -n "*"
        let "j--"
    done
    j=$i 
    while [[ $j -gt 0 ]]
    do
        echo -n " "
        let "j--"
    done
    echo ""
done

輸出:

*    
   ***   
  *****  
 ******* 
*********

Reference

  1. linux shell 字符串操做(長度,查找,替換)詳解
  2. linux shell 數組創建及使用技巧
  3. (實驗樓)高級 bash 腳本編程指南
相關文章
相關標籤/搜索