Mic*_*ich 154 bash if-statement file-handling is-empty
我有一个名为diff.txt的文件.想检查它是否为空.做过这样的事但却无法正常工作.
if [ -s diff.txt ]
then
touch empty.txt
rm full.txt
else
touch full.txt
rm emtpy.txt
fi
Run Code Online (Sandbox Code Playgroud)
thb*_*thb 200
拼写错误很刺激,不是吗?检查你的拼写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
Run Code Online (Sandbox Code Playgroud)
我喜欢shell脚本很多,但它的一个缺点是,当你拼错时,shell无法帮助你,而像你的C++编译器这样的编译器可以帮助你.
顺便提一下,我已经交换了empty.txt
和的角色full.txt
,正如@Matthias建议的那样.
小智 62
[ -s file.name ] || echo "file is empty"
Run Code Online (Sandbox Code Playgroud)
Sur*_*rya 46
[[-s file]] - >检查文件的大小是否大于0
if [[ -s diff.txt ]]; then echo "file has something"; else echo "file is empty"; fi
Run Code Online (Sandbox Code Playgroud)
如果需要,它会检查当前目录中的所有*.txt文件; 并报告所有空文件:
for file in *.txt; do if [[ ! -s $file ]]; then echo $file; fi; done
Run Code Online (Sandbox Code Playgroud)
Noa*_*nos 11
要检查文件是否为空或只有空格,您可以使用 grep:
if [[ -z $(grep '[^[:space:]]' $filename) ]] ; then
echo "Empty file"
...
fi
Run Code Online (Sandbox Code Playgroud)
Nab*_*ikh 10
检查文件是否为空的最简单方法:
if [ -s /path-to-file/filename.txt ]
then
echo "File is not empty"
else
echo "File is empty"
fi
Run Code Online (Sandbox Code Playgroud)
你也可以单行写:
[ -s /path-to-file/filename.txt ] && echo "File is not empty" || echo "File is empty"
Run Code Online (Sandbox Code Playgroud)
当其他答案正确时,"-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
Run Code Online (Sandbox Code Playgroud)
@geedoubleya答案是我最喜欢的。
不过,我更喜欢这个
if [[ -f diff.txt && -s diff.txt ]]
then
rm -f empty.txt
touch full.txt
elif [[ -f diff.txt && ! -s diff.txt ]]
then
rm -f full.txt
touch empty.txt
else
echo "File diff.txt does not exist"
fi
Run Code Online (Sandbox Code Playgroud)
[[ -f filename && ! -s filename ]] && echo "filename exists and is empty"
Run Code Online (Sandbox Code Playgroud)