Shell編程基礎總結

Shell編程基礎總結

#!/bin/bash
#This is my first shell script.
echo -n "The current date and time is:"
date
who
echo -n "The current users is:"
who | wc -l

第1行中的“#!/bin/bash“用來指定執行腳本的shell爲bash。如果要在腳本中指定執行的shell,必須在第1行指定。若沒有指定,就會使用當前正在使用的shell來指定該腳本。


執行 shell 腳本的方法

  • 以輸入重定向的方式讓shell從腳本中讀取命令並執行
 [root@localhost test]# bash<sysinfo
  • 以腳本名作爲shell命令的參數,形式爲:shell名 腳本名 [參數]
[root@localhost test]# bash sysinfo
  • 使用(.)命令,shell的一個內部命令,表示當前正在使用的shell。
 [root@localhost test]# . sysinfo
  • 使用chmod命令增加腳本的執行權限,然後再提示符下通過腳本名來執行。
[root@localhost test]# ls -l sysinfo
-rw-r--r--. 1 root root 137 1月  19 10:22 sysinfo
[root@localhost test]# chmod a+x sysinfo
[root@localhost test]# ./sysinfo
The current date and time is:20180119日 星期五 10:30:25 CST
root     :0           2018-01-19 10:19 (:0)
root     pts/0        2018-01-19 10:20 (192.168.1.18)
The current users is:2

shell 變量

變量名=變量值

filename=/home/student/test

注意:等號的左右兩邊不能有空格。變量名是以字母和下劃線開頭的字母、數字和下劃線字符序列,且區分大小寫。
若給變量值中含有空格,需要用雙引號括起來。如:

name="Zhang San"

要引用變量,需要在變量名前加”$”符號。如:

echo $name

env 命令

可以在shell中使用evn命令列出已經定義的所有環境變量。

[root@localhost ~]# env | more
XDG_SESSION_ID=3
HOSTNAME=localhost
SELINUX_ROLE_REQUESTED=
TERM=xterm
SHELL=/bin/bash
HISTSIZE=1000
SSH_CLIENT=192.168.1.18 51528 22
SELINUX_USE_CURRENT_RANGE=
SSH_TTY=/dev/pts/0
USER=root
...

這裏寫圖片描述


位置變量

在執行shell腳本時允許命令行給出傳遞給shell腳本的參數,這些參數被存儲在變量名爲0,1,2,…的特殊變量裏,稱爲位置變量。因爲這些變量名時與命令行上參數的位置相對應的。

#!/bin/bash
#This script shows how to use th position variable.
echo "The number of command line parameters is $#"
echo "The command line parameters is: $*"
echo "The script name is $0"
echo "The first parameter is $1"
echo "The second parameter is $2"
echo "The third parameter is $3"

執行如下:

[root@localhost test]# bash showposvar one two three
The number of command line parameters is 3
The command line parameters is: one two three
The script name is showposvar
The first parameter is one
The second parameter is two
The third parameter is three

條件測試

test condition

[ condition ]

這兩種方式時等價的,第1種是使用shell內部的test命令,第2種是用方括號代替test。注意,方括號中條件的左右必須有空格,其中的測試條件可以是數值測試、字符串測試或文件測試。

這裏寫圖片描述


if 分支結構

if 條件測試1
then
commands_1
elif 條件測試2
then
commands_2
elif 條件測試3
then
commands_3

else
commands_n
fi

fi(if的反寫)必須與if成對出現。elif和else分支根據實際需要,可有可無。

實例:

#!/bin/bash
#A script using the if structrue.
if [ -f $1 ]
then
   echo "$1 is an ordinary file."
   cat $1
elif [ -d $1 ]
then
   echo "$1 is an directory"
   ls $1
else
   echo "$1 is neither an ordinary file nor a direcotry."
fi

執行如下:

[root@localhost test]# bash testif /usr/
/usr/ is an directory
bin  games    lib    libexec  sbin   src   tmp
etc  include  lib64  local    share  test

case 分支結構

case 字符串 in
匹配字符串 1)
commands_1;;
匹配字符串 2)
commands_2;;
… *)
commands_n;;
esac

若沒找到匹配的字符串,就執行星號(*)後面的commands_n.匹配字符串可以使用通配符。

實例:

#!/bin/bash
#A script using th case structrue.
#display a menu
echo "***********"
echo "1 Download"
echo "2 Upload"
echo "3 Exit"
echo "***********"
echo -n "Please enter a choice:"
#read th user choice form keyboard
read choice
case $choice in
1|D)
   echo "You select th download menu";;
2|U)
   echo "You select the uplaod menu";;
3|E)
   echo "You select the exit menu"
   exit;;
*)
   echo "Sorry,your choice is not a valid choice";;
esac

執行如下:

[root@localhost test]# bash testcase
***********
1 Download
2 Upload
3 Exit
***********
Please enter a choice:1
You select th download menu

循環結構

while 條件測試
do
comands
done

until 條件測試
do
commands
done
當條件測試結果爲假時執行。

for 變量 in 值表
do
commands
done

其中的值可以時命令行實際參數,此時變量將依次取位置變量(從$1開始)的值,對每個位置變量執行一次循環體,循環體執行的次數等於命令行實際參數的個數。此時的for語句可是書寫成如下形式:

for 變量 in $*
do
commands
done

for 變量
do
commands
done

實例:下面的shell腳本將命令行參數所指定的文件或目錄依次複製到當前目錄下新建的mydir目錄中。

#!/bin/bash
#A script to copy file
mkdir mydir
for file
do
  cp -r $file mydir
done

read 命令

從標準輸入中讀取用戶輸入,並將其存儲在用戶自定義變量中。這是程序與用戶交換的重要方法。

#!/bin/bash
#A script using read command
echo -n  "Please input some words:"
read a b c
echo "a=$a"
echo "b=$b"
echo "c=$c"

命令置換

命令置換可以將一個命令的輸出用做另一個命令的參數。命令置換用倒引號(`)(Esc 鍵下面的)括起來的部分。執行時,會將命令執行結果展示在倒引號部分。

#!/bing/bash
#A script using comand replacement
echo "The current directory:pwd"
echo "The current directory:`pwd`"
path=`pwd`
echo $path

執行如下:

[root@localhost test]# bash testcom
The current directory:pwd
The current directory:/usr/test
/usr/test

set 命令

給位置變量賦值,這也是在程序中給位置變量賦值的一種方法。


#!/bin/bash
#A script using the shift command
until [ -z $1 ]
do
  echo $1
  shift
done
echo $0

執行如下:

[root@localhost test]# bash testset
one two three
2018年 01月 19日 星期五 12:06:13 CST
2018年 01月 19日

shift 命令

參數向左移動,形式爲:shift n
.若未帶參數,缺省是向左移動1位。

#!/bin/bash
#A script using the shift command
until [ -z $1 ]
do
  echo $1
  shift
done
echo $0

執行如下:

[root@localhost test]# bash testshift  one two thredd
one
two
thredd
testshift

expr 命令

處理算術運算,形式爲:expr expression
注意:運算符號左右必須有空格。 特殊字符如 *、%、(、)、>、<等,前面叫“\”。

這裏寫圖片描述


[root@localhost test]# expr 3 + 1
4

[root@localhost test]# expr 2 \* 3
6

let 命令

也是來處理算術運算,它包括了expr. 形式爲: let expressiong 或者 ((expression))
注意:let中的變量利用變量名直接訪問,不需要在簽名加$符號。表達式之間也不需要有空格。乘號也不需要加前導符。取得表達式的值,可採用$((表達式))。


[root@localhost test]# i=5
[root@localhost test]# let i=i*6
[root@localhost test]# echo $i
30
[root@localhost test]# echo $((3*2))
6

break 和 continue 命令

break 命令用來結束循環,將程序流程轉向循環結束的下一條命令。語法形式爲:
break n
其中,n爲跳出循環的層數(嵌套循環),若不帶參數,默認爲1。

continue 命令則結束本次循環,進入下一次循環。語法形式爲:
continue n
其中,n爲結束的循環次數,缺省值爲1。

#!/bin/bash
#A script using the break and continue commad
count=0
while true
do
  read key
  if [ $key = q ]
  then
      break
  elif [ $key = c ]
  then
      continue
  else
      echo $key
      count=$((count+1))
  fi
done
echo "count=$count"

執行如下:


[root@localhost test]# bash testbreak
k
k
h
h
c
g
g
q
count=3

exit 命令

shell的內部命令,在腳本中用來立即退出正在執行的腳本。語法形式:
exit n
其中,n爲退出狀態,若沒有提供,則設爲執行的最後一條命令的退出值。


here 文檔

又稱即時文檔,是另一種形式的輸入重定向,提供了在腳本程序中向一條命令傳遞輸入的方法,形式:
命令 [參數] <<標記符
文檔正文
標記符

標記符由用戶自定義,必須成對出現。

#!/bin/bash
cat << !HERE!
This is a here document.
Thank you!
!HERE!

執行如下:


[root@localhost test]# bash testhere
This is a here document.
Thank you!

信號

在shell中提供了用來捕捉信號的trap命令(比如用戶按下鍵盤的Ctrl+c組合鍵,在執行的shell腳本有時需要捕捉這個信號,進行特殊處理),該命令對收到的信號有三種處理方式:
1.執行指定命令來處理信號,其使用形式: trap “命令序列” 信號列表
當進程捕捉到信號列表中指定的信號時,將執行命令序列中的命令。信號列表可以使用信號名或者對應的信號編號,信號之間用空格隔開。
2.忽略信號,其使用形式爲:trap “” 信號列表
當收到信號列表中指定的信號時就好像沒發生一樣,信號被忽略。
3.進行缺省處理,信號的缺省處理是立刻結束收到信號的進程。要恢復信號的缺省處理功能,可使用如下形式:trap 信號列表。

這裏寫圖片描述

#!/bin/bash
#A script using the trap command
trap "echo I have recieved SIGINT" SIGINT
echo "Please input Ctrl+c to tese the trap command."
read key1
echo $key1
trap 2
echo "Please input Ctrl+c to test the recoved default processing."
read key2
echo $key2

執行如下:

[root@localhost test]# bash testsig
Please input Ctrl+c to tese the trap command.
^CI have recieved SIGINT


Please input Ctrl+c to test the recoved default processing.
^C
[root@localhost test]#

函數

函數定義語法爲:
函數名()
{
commands
}

#!/bin/bash
#A script using th funciton
#shell 函數小事例
myfunc()
{
 echo "function begin"
 let "c=a+b"
 echo $c
 echo "The paramters of the function is: $1 $2 $3"
 echo "function end"
}

a=1
b=2
c=0
myfunc one two three
echo "a=$a b=$b c=$c"

執行如下:

[root@localhost test]# bash testfunc
function begin
3
The paramters of the function is: one two three
function end
a=1 b=2 c=3

跟蹤和調試

set命令
參數:
-n:讀取一遍腳本中的命令但不執行,用來在執行程序前檢查腳本中的語法錯誤。
-x:顯示在完成參數及命令替換完成後腳本文件中的命令,並在行首顯示“+”號。可用來跟蹤和調試腳本。
-v:與-x選項類似,但會顯示變量替換前的命令行。
開始調試:set -x
關閉調試:set +x


#!/bin/bash
#A script using the break and continue commad
set -x
count=0
while true
do
  read key
  if [ $key = q ]
  then
      break
  elif [ $key = c ]
  then
      continue
  else
      echo $key
      count=$((count+1))
  fi
done
echo "count=$count"
set +x

執行如下:

[root@localhost test]# bash testbreak
+ count=0
+ true
+ read key
w+ count=0
+ true
+ read key
w
+ '[' w = q ']'
+ '[' w = c ']'
+ echo w
w
+ count=1
+ true
+ read key
w
+ '[' w = q ']'
+ '[' w = c ']'
+ echo w
w
+ count=2
+ true
+ read key
c
+ '[' c = q ']'
+ '[' c = c ']'
+ continue
+ true
+ read key
q
+ '[' q = q ']'
+ break
+ echo count=2
count=2
+ set +x
[root@localhost test]#

轉載請標明出處:http://blog.csdn.net/renli2549/article/details/79105587

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章