shell程式設計基礎

2021-09-06 16:51:05 字數 2594 閱讀 6599

(1)它必須以例如以下行開始(必須放在檔案的第一行):

# !/bin/sh

符號#!用來告訴系統執行該指令碼的程式,本例使用/bin/sh。編輯結束並儲存後,假設要執行該指令碼,必須先使其可執行:

chmod +x filename

此後在該指令碼所在資料夾下,輸入 ./filename 就可以執行該指令碼。

(2)變數賦值和引用。shell程式設計中,使用變數無需事先宣告,須要給變數賦值時,能夠這麼寫:  變數名=值 。

要取用乙個變數的值,僅僅需在變數名前面加乙個$ ( 注意: 給變數賦值的時候,不能在"="兩邊留空格 ) 

# 對字串變數賦值:

a="hello world"  

# 列印字串變數a的值:

echo "a is:" $a

執行結果:a is: hello world

假設是變數不用輸出到終端,直接在sh檔案內部呼叫,使用單引號就可以:

product='real6410'

呼叫到的地方使用:

mkdir -p out/target/product/$product/obj/lib

(3)if 語句。"if"表示式假設條件為真,則執行then後的部分:

if ....; then

....

elif ....; then

....

else

....

fi通經常使用" [ ] "來表示條件測試,注意這裡的空格非常重要,要確保方括號前後的空格。比如:

[ -f "somefile" ] :推斷是否是乙個檔案

[ -x "/bin/ls" ] :推斷/bin/ls是否存在並有可執行許可權

[ -n "$var" ] :推斷$var變數是否有值

[ "$a" = "$b" ] :推斷$a和$b是否相等

(4)迴圈。

while ...; do

....

done

僅僅要測試表示式條件為真,則while迴圈將一直執行。keyword"break"用來跳出迴圈,而keyword」continue」則能夠跳過乙個迴圈的餘下部分,直接跳到下一次迴圈中。

(5)函式功能

在sh中能夠定義某段類似於函式的整合語句段,在名字前使用function申明。方法如:

function real6410_prebuild()

之後,在其它地方直接使用real6410_prebuild即可了。

(6)sync

同步檔案控制代碼, 重新整理全部未寫入硬碟的資料。

(7)例項,可執行指令碼update的內容例如以下。

#!/bin/bash

if [ "$1" = "" ]; then

echo "please input resolution,"

echo "such as: qvga, wqvga, wvga, hvga"

exit

fip=$1

./tool/bmp_to_raw ./temp0.raw ./$p/"$_uboot".bmp

./tool/bmp_to_raw ./temp1.raw ./$p/"$_battery00".bmp

./tool/bmp_to_raw ./temp2.raw ./$p/"$_battery02".bmp

./tool/bmp_to_raw ./te***.raw ./$p/"$_battery04".bmp

./tool/bmp_to_raw ./temp4.raw ./$p/"$_battery06".bmp

./tool/bmp_to_raw ./temp5.raw ./$p/"$_battery08".bmp

./tool/bmp_to_raw ./temp6.raw ./$p/"$_low_battery1".bmp

./tool/bmp_to_raw ./temp7.raw ./$p/"$_low_battery2".bmp

./tool/bmp_to_raw ./temp8.raw ./$p/"$_batteryfull".bmp

./tool/bmp_to_raw ./temp9.raw ./$p/"$_charger_ov".bmp

./tool/bmp_to_raw ./boot_logo ./$p/"$_kernel".bmp

./tool/zpipe -l 9 ./"$.raw" temp0.raw temp1.raw temp2.raw te***.raw temp4.raw temp5.raw temp6.raw temp7.raw temp8.raw temp9.raw

rm -rf ./temp0.raw ./temp1.raw ./temp2.raw ./te***.raw ./temp4.raw ./temp5.raw ./temp6.raw ./temp7.raw ./temp8.raw ./temp9.raw ./bootlogo.raw

echo "conversion finished"

說明:$1表示第乙個引數;以上命令依次執行。執行時用./update ***就能夠執行,可是還有些時候的shell指令碼是用. 或者source來執行的,這些指令碼是須要在當前shell環境下執行的(不會建立子程序),也即包括內建命令的指令碼。

參考原文:

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 ...