[Linux / UNIX] 找出Bash Shell中是否存在帶有條件表達式的檔案

Richard Tsai
3 min readMar 2, 2020

--

範例程式:

modprobe ipmi-si
modprobe ipmi-devintf
# get hard driver number and write to /root/device_count
# get pci dirver number and append to /root/device_count
# get memory capacity and append to /root/device_count
gen_device () {
if [ -f /root/device_count ]; then
rm /root/device_count > /dev/null
else
touch /root/device_count
fi
lsscsi | wc -l >> /root/device_count
lspci | wc -l >> /root/device_count
cat /proc/meminfo | awk '/MemTotal:/ {print $2}' >> /root/device_count
}
cycle () {
if [[ ($(cat /root/device_count|sed -n 1p) -eq $(lsscsi | wc -l) \
&& $(cat /root/device_count|sed -n 2p) -eq $(lspci | wc -l) \
&& $(cat /root/device_count|sed -n 3p) -eq $(cat /proc/meminfo | awk '/MemTotal:/ {print $2}') ) ]]
then
date >> /root/power_cycle_log
ipmitool chassis power cycle
else
echo "Device Lost"
exit 0
fi
}
[ ! -e /root/gened ] || cycle
[ -e /root/device_count ] || gen_device
echo "Disks :" $(lsscsi | wc -l)
echo "Device :" $(lspci | wc -l)
echo "Mmeory :" $(dmidecode -t 16|grep -i Maximum\ Capacity|head -n 1| awk '{print $3}')
echo 1 > gened
read -p "Please check your device match your system ,and press enter start power cycle test"
cycle

其中在檔案是否存在的判斷上使用到二種不同的參數: -e 和 -f

用以下指令可以查到

# man bash

從原文來看,-e 參數可以判斷的檔案類型更多。

以下是Google 到的參考資料:

https://www.cyberciti.biz/tips/find-out-if-file-exists-with-conditional-expressions.html

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Richard Tsai
Richard Tsai

Written by Richard Tsai

人的大腦是用來思考, 解決問題, 不是拿來當記事本

No responses yet

Write a response