shell腳本從入門到精通(中級)之提高篇
shell 腳本入門到精通(中級)
一、shell 腳本的執行
二、輸出格式化
一、shell 腳本的執行
1. 腳本執行的4種方法
$ ls /tmp/test.sh
/tmp/test.sh
#!/bin/bash
# test.sh
# 這裏借助SHLVL這個變量,SHLVL可以顯示shell的層級,
# 每啟動一個shell,這個值就加1
echo "shell level :$SHLVL"
echo "hello world!"
切換到shell腳本所在目錄執行
root@localhost:/# cd /tmp/
root@localhost:/tmp# chmod +x test.sh
root@localhost:/tmp# ./test.sh
shell level :2
hello world!以絕對路徑執行
root@localhost:~# chmod +x /tmp/test.sh
root@localhost:~# /tmp/test.sh
shell level :2
hello world!直接使用bash或sh 來執行bash shell腳本
root@localhost:/tmp# bash test.sh
shell level :2
hello world!
root@localhost:/tmp# sh test.sh
shell level :1
hello world!在當前shell 環境中執行
root@localhost:/tmp# . test.sh
shell level :1
hello world!
root@localhost:/tmp# source test.sh
shell level :1
hello world!
總結:註意看SHLVL的值,前3種方式都在子shell中執行(sh除外),第4種在當前shell種執行。
2.調試腳本
bash -x script.sh 跟蹤調試shell腳本
例:
root@localhost:/tmp# bash -x test.sh
+ echo ‘shell level :2‘
shell level :2
+ echo ‘hello world!‘
hello world!
-x 打印所執行的每一行命令以及當前狀態
set -x : 在執行時顯示參數和命令
set +x : 禁止調試
set -v : 當命令進行讀取時顯示輸入
set +v : 禁止打印輸入
二、輸出格式化
1. C語言風格的格式化
#!/bin/bash
printf "%-5s %-10s %-4s\n" NO. Name Mark
printf "%-5s %-10s %-4.2f\n" 1 Sarath 80.3456
printf "%-5s %-10s %-4.2f\n" 2 James 90.9989
root@localhost:/tmp# ./test.sh
NO. Name Mark
1 Sarath 80.35
2 James 91.00
2. echo
- 不換行
echo -n "hello world" - 轉義
echo -e "hello\t\tworld" - 彩色輸出
顏色 | 重置 | 黑 | 紅 | 綠 | 黃 | 藍 | 紫 | 青 | 白 |
---|---|---|---|---|---|---|---|---|---|
前景色 | 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"
或
echo -e "\033[47;31m This is red test \033[0m"
shell腳本從入門到精通(中級)之提高篇