我有一個名爲diff.txt的文件。要檢查它是否爲空。做了這樣的事情,但不能得到它的工作。如何檢查文件在Bash中是否爲空?
if [ -s diff.txt ]
then
touch empty.txt
rm full.txt
else
touch full.txt
rm emtpy.txt
fi
我有一個名爲diff.txt的文件。要檢查它是否爲空。做了這樣的事情,但不能得到它的工作。如何檢查文件在Bash中是否爲空?
if [ -s diff.txt ]
then
touch empty.txt
rm full.txt
else
touch full.txt
rm emtpy.txt
fi
拼寫錯誤令人不快,是不是?檢查拼寫empty
,但隨後也試試這個:
#!/bin/bash -e
if [ -s diff.txt ]
then
rm -f empty.txt
touch full.txt
else
rm -f full.txt
touch empty.txt
fi
我喜歡shell腳本很多,但它的一個缺點是,外殼也幫不了你,當你拼錯,而像C++編譯器可以編譯幫你。
順便說一句,我已經交換了empty.txt
和full.txt
的角色,正如@Matthias所暗示的那樣。
殼可以幫助拼寫錯誤。 '空= empty.txt;充分= full.txt; DIFF = diff.txt;如果[-s $ {diff?}];那麼r = $ {empty?} t = $ {full?};否則r = $ {full?} t = $ {empty?};網絡連接; rm $ {r?};觸摸$ {t?}' – 2016-09-13 15:31:48
使用shellcheck工具可以發現拼寫錯誤。 – Yokai 2016-10-03 03:30:09
如果文件不存在,這肯定會失敗嗎?這應該是一個檢查,如果文件只是空的。 – geedoubleya 2017-10-05 11:31:52
[ -s file.name ] || echo "file is empty"
[[-s file.name]] && echo「full」||回聲「空」 – McPeppr 2018-01-29 20:27:10
[[-s文件〕〕 - >檢查如果文件具有尺寸大於0
if [[ -s diff.txt ]]; then echo "file has something"; else echo "file is empty"; fi
如果需要,該檢查在當前目錄中的所有* .txt文件;並報告所有的空文件:
for file in $(ls *.txt); do if [[ ! -s $file ]]; then echo $file; fi; done
而其他的答案是正確的,使用"-s"
選項也將顯示該文件是即使該文件不存在空。
通過添加此額外檢查"-f"
以查看文件是否先存在,我們確保結果是正確的。
if [ -f diff.txt ]
then
if [ -s diff.txt ]
then
rm -f empty.txt
touch full.txt
else
rm -f full.txt
touch empty.txt
fi
else
echo "File diff.txt does not exist"
fi
[-s FILE]如果FILE存在並且其大小大於零,則爲真。 因此,如果「diff.txt」不爲空,則會得到「empty.txt」。 – Matthias 2012-04-01 13:48:43
PS:如果你想檢查一個實際的'diff'調用,只需檢查返回值:'if diff foo.txt bar.txt;那麼回聲'沒有區別' – l0b0 2012-04-02 13:13:59
測試可以否定:'如果[! -s diff.txt];然後回顯「是空的」;否則回顯「有些東西」; fi' – 2014-06-13 20:44:58