命令替換
| 語法 | 說明 | |
|---|---|---|
| 方法一 | `command` | 無 |
| 方法二 | $(command) | 無 |
說明:命令替換是指將命令的輸出結(jié)果賦值給某個變量。``和$()兩者是等價的。
注意:$(())與$()不是同一個東西,比較容易混淆。$(())主要用來進(jìn)行整數(shù)運算,包括加減乘除,引用變量前面可以加$,也可以不加$。
示例
例子1:獲取系統(tǒng)的所有用戶并輸出。
#!/bin/bash
index=1
for user in `cat /etc/passwd | cut -d ":" -f 1`
do
echo "This is $index user: $user"
index=$(($index + 1))
done
輸出:
This is 1 user: User
This is 2 user: Database
This is 3 user: Note
This is 4 user: that
......
這里index=$(($index + 1))并不是命令替換,而是整數(shù)運算。cut命令對輸入的字符進(jìn)行分割,-d ":"表示:為分割符分割成多個子串。-f 1表示獲取分割子串中的第一個。
例子2:根據(jù)系統(tǒng)時間計算今年或明年。
$ echo "This is $(($(date +%Y) + 1)) year"
輸出:
This is 2023 year
例子3:根據(jù)系統(tǒng)時間獲取今年還剩下多少星期,已經(jīng)過了多少星期。
$ echo "This year have passed $(($(date +%j) / 7)) weaks"
$ echo "This is $(((365 - $(date +%j)) / 7)) days before new year"
輸出:
This year have passed 3 weaks
This is 49 days before new year
例子4:判定nginx進(jìn)程是否存在,若不存在則自動拉起該進(jìn)程。
nginx_process_num=$(ps -ef | grep nginx | grep -v grep | wc -l)
if [ $nginx_process_num -eq 0 ]; then
systemctl start nginx
fi
這里將ps -ef | grep nginx | grep -v grep | wc -l命令執(zhí)行之后的結(jié)果賦值給nginx_process_num變量。