shell 腳本基礎

  1. 指定當前腳本執行的 shell 環境,若是須要執行,能夠使用 chmod 777 xxx.sh 將 shell 腳本修改成可執行權限,或者使用 /bin/bash xxx.sh
#! /bin/bash 複製代碼
  1. 輸出一句話
echo "Hello World!"
複製代碼
  1. 從鍵盤上獲取一個值複製給變量 PERSON
echo "What is your name"
將輸入的值複製給變量 PERSON.
read PERSON
# $PERSON 取出變量的值
echo "Hello $PERSON "
複製代碼
  1. 定義變量

定義變量不能使用 shell 的關鍵字,可以使用 help 命令查看變量的等號 =左右不能有空格.使用變量在前面加上美圓符號 $ 或 ${}, 良好的編程方式是加上 {}, 放置變量的界限不清楚c++

url=http://www.baidu.com
echo ${url}
name='百度一下'
echo ${name}
author="Kevin"
echo ${author}
複製代碼
  1. 修改變量的值
url=http://www.taobao.com
echo ${url}
複製代碼
  1. 單引號和雙引號的區別

單引號的會按照原來的方式輸出,哪怕其中有變量也不會處理,雙引號會解析變量和命令web

url=http://www.huawei.com
website1='歡迎來到: ${url}'
website2="歡迎來到: ${url}"
echo ${website1}
echo ${website2}
複製代碼
  1. 將命令的結果賦值給變量,請記住這裏 `` 並非單引號,固然你也能夠使用 $() 方式
variable=`cat log.txt`
variable=$(cat log.txt)
echo ${variable}
複製代碼
  1. 只讀變量

經過使用 readonly 將變量定義爲只讀變量,這個值就不能再修改shell

myUrl="http://www.baidu.com"
readonly myUrl
# 提示錯誤: 變量不能修改
# myUrl="http://www.huawei.com"
複製代碼
  1. 刪除變量

unset 只能刪除非 readonly 的變量編程

mUrl="http://www.huawei.com"
unset mUrl
echo ${mUrl}
複製代碼
  1. 特殊變量

$ 符號表示當前進程的 ID, 即 pid數組

$0 當前腳本的文件名bash

$n 傳遞給腳本或函數的參數,n 是一個數字,表示第幾個參數,第一個是 $1, 第二個是$2less

$# 傳遞給腳本或函數的參數個數函數

$@ 傳遞給腳本或函數的全部參數, 被雙引號包含時與 $* 稍有不一樣工具

$* 傳遞給腳本或函數的全部參數測試

$? 上個命令的退出狀態,或函數的返回值

$$當前進程的 pid

echo $$
# 當前腳本的文件名
echo $0
複製代碼
  1. 命令行參數
echo "First Name: $0"
echo "First Parameter: $1"
echo "Second Parameter: $2"
echo "Quoted Values: $@"
echo "Quoted Values: $*"
echo "Total Number of Parameters: $#"
複製代碼
  1. $* 和 $@ 的區別
echo "\$*=" $*
echo "\"\$*\"=" "$*"

echo "\$@=" $@
echo "\"\$@\"=" "$@"

echo "print each param from \$*"
for var in $*
do
    echo "${var}"
done

echo "print each param from \$@"
for var in $@
do  
    echo "$var"
done

echo "print each param from \"\$*\""
for var in "$*"
do  
    echo "$var"
done

echo "print each param from \"\$@\""
for var in "$@"
do
    echo "$var"
done
複製代碼
  1. 命令替換
DATE=`date`
echo "Date is ${DATE}"

USERS=`who | wc -l`
echo "Logged in user are ${USERS}"

UP=`date; uptime`
echo "Uptime is ${UP}"
複製代碼
  1. 變量替換

${var:-""} 若是變量 var 爲空將不會賦值

echo ${var13:-"Wariable is not set"}
echo "1 - value of var is ${var13}"

# ${var:=""} 若是變量爲空,將會被複製成後面的值
echo ${var13:="Variable is not set"}
echo "2 - value of var is ${var13}"

# unset var13,刪除 var13
unset var13
# ${var:} 若是變量爲空,則會返回後面的值,但不會賦值給 var
echo ${var13:+"This is default vale"}
echo "3 - value of var is ${var13}"

# ${var:+""} 若是 var 有值,返回 word, 但不改變 var 的值
var13="Prefix"
echo ${var13:+"This is default value"}
echo "4 - value of var is ${var13}"

# ${var:?""} 若是 var 爲空或被刪除,會將後面的值做爲錯誤輸出,並會中止腳本運行
echo ${var13:?"Print this message"}
echo "5 - value of var is ${var13}"

# var14 未定義,將 This is a error message 輸出
# echo ${var14:?"This is a error message"}
# echo "6 - value of var is ${var14}"

複製代碼
  1. 運算符

expr 是一個表達式計算工具 2 + 2 運算符之間必須有空格

var14=$(expr 2 + 2)
echo "Total value: ${var14}"

a14=10
b14=20
# 加法
var14=`expr $a14 + $b14`
echo "a + b : $var14"

var14=`expr $a14 - $b14`
echo "a - b : $var14"

var14=`expr $a14 \* $b14`
echo "a * b : $var14"

var14=`expr $a14 / $b14`
echo "a / b : $var14"

var14=`expr $a14 % $b14`
echo "a % b : $var14"

if [ $a14 == $b14 ] 
then 
    echo "a is euqal to b"
fi

if [ $a14 != $b14 ] 
then    
    echo "a is not equal b"
fi

複製代碼
  1. 關係運算符.
a15=10
b15=20

# 檢查兩個值是否相等
if [ $a15 -eq $b15 ] 
then    
    echo "$a15 -eq $b15 : a is equal to b"
else 
    echo "$a15 -eq $b15 : a is not equal to b"    
fi 

# 檢查兩個值是否不相等,不想等返回 true
if [ $a15 -ne $b15 ] 
then 
    echo "$a15 -ne $b15: a is not equal to b"
else 
    echo "$a15 -ne $b15: a is equal to b"    
fi

# 檢查左邊的值是否大於右邊的,若是是,返回 true
if [ $a15 -gt $b15 ] 
then 
    echo "$a15 -gt $b15 : a is greater than b"
else
    echo "$a15 -gt $b15 : a is not greater than b"    
fi

# 檢查左邊的值是否小於右邊的,若是是返回 true
if [ $a15 -lt $b15 ] 
then    
    echo "$a15 -lt $b15 : a is less than b"
else 
    echo "$a15 -lt $b15 : a is not less than b"
fi

# 檢查左邊的值是否大於等於右邊的值, 若是是返回true
if [ $a15 -ge $b15 ] 
then
    echo "$a15 -ge $b15: a is greater or equal to b"
else 
     echo "$a15 -ge $b15: a is not greater or equal to b" 
fi

# 檢查左邊的值是否小於等於右邊的值, 若是是返回 true
if [ $a15 -le $b15 ] 
then
    echo "$a15 -le $b15: a is less or euqal to b"
else 
    echo "$a15 -le $b15: a is not less or euqal to b"
fi
複製代碼
  1. 布爾運算符.
a16=10
b16=20

# 判斷兩個值不相等,若是不相等返回 true
if [ $a16 != $b16 ] 
then
    echo "$a16 != $b16 : a is not equal to b"
else 
    echo "$a16 != $b16 : a is equal to b"
fi

# a16 是否小於 100 且 b16 大於 15
if [ $a16 -lt 100 -a $b16 -gt 15 ] 
then 
    echo "$a16 -lt 100 -a $b16 -gt 15 true"
else 
    echo "$a16 -lt 100 -a $b16 -gt 15 false"
fi

# a16 是否小於 100 或 b16 大於 100
if [ $a16 -lt 100 -o $b16 -gt 100 ] 
then 
    echo "$a16 -lt 100 -o $b16 -gt 100 true"
else 
    echo "$a16 -lt 100 -o $b16 -gt 100 false"
fi

# a16 小於 5 或 b16 大於 100
if [ $a16 -lt 5 -o $b16 -gt 100 ] 
then 
    echo "$a16 -lt 5 -o $b16 -100 15 true"
else 
    echo "$a16 -lt 5 -o $b16 -100 15 false"
fi
複製代碼
  1. 字符串運算符
a17="abc"
b17="efg"

if [ $a17 = $b17 ] 
then
    echo "$a17 = $b17 : a is equal to b"
else 
    echo "$a17 = $b17 : a is not equal to b"
fi

if [ $a17 != $b17 ] 
then
    echo "$a17 = $b17 : a is not equal to b"
else 
    echo "$a17 = $b17 : a is equal to b"
fi

if [ -z $a17 ] 
then
    echo "-z $a : string length is zero"
else 
    echo "-z $a : string length is not zero"
fi

if [ -n $a17 ]
then 
    echo "-n $a17: string length is not zero."
else 
    echo "-n $a17: string length is zero."
fi

if [ $a17 ]
then 
    echo "$a17 : string is not empty"
else 
    echo "$a17 : string is empty"
fi

複製代碼
  1. 文件測試運算符
file="./log.txt"

# 檢查文件是否可讀
if [ -r $file ] 
then
    echo "File has read access."
else 
    echo "File does not have read access."
fi

# 檢查文件是否爲空.
if [ -s $file ]
then
    echo "File size is zero"
else 
    echo "File size is not zero"
fi

# 檢查文件是否存在
if [ -e $file ]
then
    echo "File exist"
else 
    echo "File does not exist"
fi

# 檢查是不是目錄.
if [ -d $file ] 
then
    echo "File is a directory."
else
    echo "This is not a directory"
fi

# 檢查文件是否普通文件.
if [ -f $file ]
then
    echo "File is an ordinary file"
else 
    echo "This is sepcial file"
fi

# 檢查文件是否可執行.
if [ -x $file ]
then 
    echo "File has execute permission."
else
    echo "File does not have execute permission."
fi

# 檢查文件是否可寫
if [ -w $file ]
then
    echo "File has write permission."
else 
    echo "File does not have write permission."
fi

複製代碼
  1. 字符串相關
# 獲取字符串長度
string="abcd"
echo ${#string}

# 截取字符串
string="hello world"
echo ${#string:1:5}

# 查找字符串
#string="I love you."
#echo `expr index "$string" is`

# 拼接字符串
string="hello"
string1="world"
string2="shell"

string3="$string $string1, $string2"
echo $string3
複製代碼
  1. 數組相關
# 定義數組
array=(1 2 3 4 5 6 "zhangsan")
# 獲取指定元素 ${array_name[index]}
valuen=${array[6]}
echo "valuen: $valuen"
# 獲取數組中全部元素, ${array_name[*]} 或 ${array_name[@]}
echo "array: ${array[@]}"
# 獲取數組的長度, 跟字符串獲取長度方式相同:${#array_name[@]} 或 ${#array_name[*]}
length=${#array[*]}
echo "array length: ${length}"
# 獲取數組中單個元素的長度
lengthn=${#array[6]}
echo "The element length of array: $lengthn"

複製代碼
  1. echo
#重定向到文件
file="./log.txt"
echo "Hello Echo." > $file
複製代碼
  1. 條件判斷語句
a21=20
b21=30

if [ $a21 -gt $b21 ]
then    
    echo "a21 gt b21"
else
    echo "a21 lt b21"
fi

if [ $a21 -eq 100 ]
then
    echo "a21 -eq 100"
elif [ $a21 -eq 50 ]
then    
    echo "a21 -eq 50"
elif [ $a21 -le 20 ]
then
    echo "a21 -eq 20"
else
    echo "a21 -lt 20"
fi


複製代碼
  1. test
數值測試.
num1=10
num2=20

if test ${num1} -eq ${num2}
then 
    echo "The two numbers are equal!"
else 
    echo "The two numbers are not equal"
fi    

# 字符串測試
num1="abc"
num2=abc

if test num1=num2
then
    echo "The two strings are equal!"
else 
    echo "The two strings are not equal!"
fi

# 文件測試
if test -e ./log.txt -o ./bash
then 
    echo "One file already exists!"
else 
    echo "The file does not exists!"
fi

if test -x ./learningShell.sh
then 
    echo "The file can execute."
else 
    echo "Them file does not execute."
fi

複製代碼
  1. case 語句
echo "Input a number between 1 to 4"
echo "Your number is: \c"

read aNum
case $aNum in
    1) echo 'you select 1'
    ;;
    2) echo 'you select 2'
    ;;
    3) echo 'you select 3'
    ;;
    *) echo 'You do not select a number between 1 to 4'
esac    

# option="${1}"
# case ${option} in 
# -f) FILE="${2}"
# echo "File name is $FILE"
# ;;
# -d) DIR="${2}"
# echo "Dir name is $DIR"
# ;;
# *)
# echo "`basename ${0}`: usage: [-f file] | [-d directory]"
# exit 1
# ;;
# esac

複製代碼
  1. for 循環
for i in 1 2  3 4 5
do  
    if [ $i -eq 0 ]
    then
        echo "The value is 0."
    elif [ $i -eq 1 ]
    then
        echo "The value is 1."   
    else
        echo "The value is others: $i"
    fi

done

# 輸出字符串.
for str in 'This is a string'
do  
    echo $str
done

# 輸出指定目錄下的文件.
for FILE in $HOME/fullstack/c++/LearningCpp/*
do
    echo $FILE
done

複製代碼
  1. wile 循環
# 遍歷輸出某個條件下的數據.
COUTER=0
while [ $COUTER -lt 5 ]
do
    COUTER=`expr $COUTER + 1`
    echo $COUTER
done

# 讀取鍵盤的數據.
# echo 'type <CTRL-D> to terminate'
# echo -n 'enter your most liked film: '
# while read FILM
# do
# echo "Yeah! greate film the $FILM"
# done


複製代碼
  1. until
a=0
until [ ! $a -lt 10 ]
do 
    echo $a
    a=$(expr $a + 1)
done

複製代碼
  1. break、continute
# 符合條件後跳出.
while :
do
    echo -n "Input a number between 1 to 5:"
    read aNum
    case $aNum in
        1|2|3|4|5) echo "Your number is ${aNum}!"
        ;;
        *)
            echo "You do not select a number between 1 to 5, game is over!"
            break
            ;;
    esac
done

# 跳到指定層
for var in 1 2 3
do 
    for var2 in 0 5 
    do 
        if [ $var -eq 2 -a $var2 -eq 0 ]
        then 
            break 2
        else 
            echo "$var $var2"
        fi
    done
done

# continue 
while :
do
    echo -n "Input a number between 1 to 5: "
    read aNum
    case $aNum in
        1|2|3|4|5) echo "Your number is ${aNumb}!"
        ;;
        0) echo "Completed!"
        break
        ;;
        *)
            echo "You do not select a number between 1 to 5!"
            continue
            echo "Game is over!"
            ;;
    esac
done
複製代碼
  1. 函數
# 定義一個函數
Hello () {
    echo "This is a function."
}

# 調用函數
Hello

# 有返回參數的函數
funcWithReturn() {
    echo "The function is to get the sum of two numbers..."
    echo -n "Input first number: "
    read aNum
    echo -n "Input another number: "
    read anotherNumber
    echo "The two numbers are ${aNum} and ${anotherNumber} !"
    return $(expr $aNum + $anotherNumber)
}

funcWithReturn

ret=$?
echo "The sum of two numbers is $ret !"

# 函數嵌套
one() {
    echo "function one."
    two
}

two() {
    echo "function two."
}

one

# 刪除函數
# unset .f one
複製代碼
  1. 函數參數

給函數傳遞參數

$# 參數個數 $* 顯示全部傳遞給函數的參數 $@ 顯示全部參數,在有引號的是不一樣 $? 函數的返回值

funcWithReturn() {
    echo "first parameter is $1 "
    echo "second parameter is $2"
    echo "third parameter is $3"
    echo "tenth parameter is ${10}"
}

funcWithReturn 1 2 3 4 5 6 7 8 9 10

複製代碼
  1. 引入外部文件

引入外部的腳本,包含的腳本能夠沒有執行權限 . xx.sh 或 source xx.sh

#. ./test.sh
source ./test.sh

echo $name

複製代碼
相關文章
相關標籤/搜索