shell程式設計基礎

2021-08-08 21:45:15 字數 2070 閱讀 7620

1、執行shell指令碼方法

. ./test.sh (需要給x許可權)

./test.sh (需要給x許可權)

sh shell.sh (不需要給x許可權)

2、變數定義

str=hello world ->echo $str ->hello world

a=cc str="hello $a" ->echo $str ->hello cc

a=cc str='hello $a' ->echo $str ->hello $a

unset a //撤銷變數a

a=`ll` 或者 a=(ll) //把ll的結果賦給a

3、特殊變數

$?:上一條命令的返回值,不成功為1

$n:第n個位置的引數

$#:引數的個數

$* 或 $@ :引數列表

--------------------下面是例子--------------------------------

#!/bin/bash

for i in $* do

echo $i

done

輸入什麼將逐個逐行輸出

4、變數運算

計算1+2:`expr 2 + 3`  //expr後有空格,2後和+後有空格

多個變數: $((1+1)*2)

5、for迴圈

for i in 1 2 3

do echo $i

done

-------------------用法分割線-----------------

for i in ;do echo $i;done

-------------------用法分割線-----------------

for ((i = 0; i <= 5; i++))

doecho "welcome $i times"

done

6、while

while condition

do expression

done

-------------------用法分割線-----------------

i=1while ((i<=3))

doecho $i

let i++

done

7、case

case $1 in

start)

echo "starting"

;;stop)

echo "stoping"

;;*)

echo "usage: 「

esac

8、read命令-讀取

read -p "please input your name:" name

echo $name

9、if

#!/bin/bash

read -p "please input your name:" name

#printf '%s\n' $name

if [ $name = root ]

then

echo "hello $,  welcome !"

elif [ $name = itcast ]

then

echo "hello $,  welcome !"

else

echo "sb, get out here !"

fi10、判斷語句

格式:[ condition ]   //注意空格,非空返回true,空返回false,0為true,>1為false

[ condition ] && echo ok || echo notok  //條件滿足ok,不滿足notok

常用判斷條件:

= 字串比較

-lt 小於

-le 小於等於

-eq 等於

-gt 大於

-ge 大於等於

-ne 不等於

-f 檔案存在並且是乙個常規的檔案

11、自定義函式-不能接收引數

#!/bin/bash

function fsum()

fsum 5 7;

echo $total,$?;

Shell 程式設計基礎

2 shell 程式設計基礎 shell 簡介認識後台程式 bash 程式設計熟悉 linux 系統下的編輯環境 熟悉linux 下的各種 shell 熟練進行 shell 程式設計熟悉 vi基本操作 熟悉emacs 的基本操作 比較不同 shell 的區別編寫乙個測試伺服器是否連通的 shell ...

shell程式設計基礎

1.熟悉shell 1.1 基本語法 bin bash shell必須以上面所示的開頭,以 開頭的語句表示注釋。1.2 新增可執行許可權 chmod u x 檔名 1.3 建立簡單的shell bin bash echo n hell user,today is date echo good luc...

shell 程式設計基礎

1.基礎正規表示式 aa 表示至少包含乙個a的行,a 匹配所有內容 匹配任意乙個字元,精準匹配 grep 提取文字中的字元 grep v root 取反不包括root的行 2.cut 命令 f第幾列 d分隔符 3.printf ni輸出n個整數 ns n個字元 m.nf m.nprintf s t ...