shell – 检查文件是否存在以及它是否包含特定的字符串

前端之家收集整理的这篇文章主要介绍了shell – 检查文件是否存在以及它是否包含特定的字符串前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想检查file2.sh是否存在,如果一个特定的单词,诗人是文件的一部分。我使用grep创建变量used_var。
#!/bin/ksh

file_name=/home/file2.sh                  
used_var=`grep "poet" $file_name`

如何检查used_var是否具有某些值?

而不是将grep的输出存储在变量中,然后检查变量是否为空,您可以这样做:
if grep -q "poet" $file_name
then
    echo "poet was found in $file_name"
fi

============

以下是一些常用的测试:

-d FILE
          FILE exists and is a directory
   -e FILE
          FILE exists
   -f FILE
          FILE exists and is a regular file
   -h FILE
          FILE exists and is a symbolic link (same as -L)
   -r FILE
          FILE exists and is readable
   -s FILE
          FILE exists and has a size greater than zero
   -w FILE
          FILE exists and is writable
   -x FILE
          FILE exists and is executable
   -z STRING
          the length of STRING is zero

例:

if [ -e "$file_name" ] && [ ! -z "$used_var" ]
then
    echo "$file_name exists and $used_var is not empty"
fi

猜你在找的Bash相关文章