1.腳本執(zhí)行的4種方法#!/bin/bash # test.sh # 這里借助SHLVL這個(gè)變量,SHLVL可以顯示shell的層級(jí), # 每啟動(dòng)一個(gè)shell,這個(gè)值就加1 echo "shell level :$SHLVL" echo "hello world!"
總結(jié):注意看SHLVL的值,前3種方式都在子shell中執(zhí)行(sh除外),第4種在當(dāng)前shell種執(zhí)行。 2.調(diào)試腳本bash -x script.sh 跟蹤調(diào)試腳本 root@localhost:/tmp# bash -x test.sh + echo 'shell level :2' shell level :2 + echo 'hello world!' hello world! -x 打印所執(zhí)行的每一行命令及當(dāng)前狀態(tài) set -x:在執(zhí)行是顯示參數(shù)和命令 set +x:禁止調(diào)試 set -v :當(dāng)命令進(jìn)行讀取時(shí)顯示輸入 set +v :當(dāng)命令進(jìn)行讀取時(shí)禁止打印輸入 3.輸出格式化1.C語(yǔ)言風(fēng)格格式化輸出#!/bin/bash printf " % -5s %-10s %-4s\n" NO. Name Mark printf " % -5s %-10s %-4.2f\n" 1 joe 80.55 printf " % -5s %-10s %-4.1f\n" 2 joe 80.5 printf " % -5s %-10s %-4.3f\n" 3 joe 80.500 2.echo1.不換行 echo -n "hello world" 2.轉(zhuǎn)義 echo -e "hello\t\tworld" 3.彩色輸出 顏色 重置 黑 紅 綠 黃 藍(lán) 紫 青 白 前景色 0 30 31 32 33 34 35 36 37 背景色 0 40 41 42 43 44 45 46 47 echo -e "\e[1;31m This is red test \e[0m" 4.數(shù)據(jù)類(lèi)型1.字符串獲取字符串長(zhǎng)度 echo ${#str} 2.數(shù)組數(shù)組的定義 方法一: arr=(1 2 3 4 5) 方法二: arr[0]=1 arr[1]=2 arr[2]=3 echo ${arr[*]} 1 2 3 打印數(shù)組中的值 root@localhost:~# arr=(1 2 3 4 5) 3.關(guān)聯(lián)數(shù)組普通數(shù)組只能使用整數(shù)作為索引值,而關(guān)聯(lián)數(shù)組可以使用任意文本作為索引值(有點(diǎn)類(lèi)似于Python中的字典,不知道這樣理解對(duì)不對(duì)),關(guān)聯(lián)數(shù)組只在bash 4.0以上支持。 bash -version 關(guān)聯(lián)數(shù)組的定義和使用 root@localhost:~# declare -A person root@localhost:~# person=([name]="Wang" [age]=18) root@localhost:~# echo ${person[name]} Wang root@localhost:~# echo ${person[age]} 18 root@localhost:~# echo ${person[*]} Wang 18 5.重定向符號(hào) 含義 用法 例 < 標(biāo)準(zhǔn)輸入 從文件中輸入 wc -l file.txt > 標(biāo)準(zhǔn)輸出 目標(biāo)文件不存在會(huì)新建一個(gè);目標(biāo)文件存在會(huì)覆蓋原內(nèi)容 echo "" > /var/www/html/index.php >> 追加到文件 目標(biāo)文件不存在會(huì)新建一個(gè);目標(biāo)文件存在會(huì)在文件末尾追加 echo "add text" >> file.txt 6.變量1.只讀變量#!/bin/bash readonly hours_per_day=24 hours_per_day=12 更改變量會(huì)觸發(fā)異常 2.展開(kāi)運(yùn)算符
|
|
來(lái)自: Coder編程 > 《待分類(lèi)》