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

ran*_*psp 32 shell ksh

我想检查是否file2.sh存在以及特定单词poet是否是文件的一部分.我grep用来创建变量used_var.

#!/bin/ksh

file_name=/home/file2.sh                  
used_var=`grep "poet" $file_name`    
Run Code Online (Sandbox Code Playgroud)

我如何检查是否used_var有一些价值?

dog*_*ane 46

不是将grep的输出存储在变量中,然后检查变量是否为空,您可以这样做:

if grep -q "poet" $file_name
then
    echo "poet was found in $file_name"
fi
Run Code Online (Sandbox Code Playgroud)

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

以下是一些常用的测试:

   -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
Run Code Online (Sandbox Code Playgroud)

例:

if [ -e "$file_name" ] && [ ! -z "$used_var" ]
then
    echo "$file_name exists and $used_var is not empty"
fi
Run Code Online (Sandbox Code Playgroud)

  • -q是“安静”的。 (2认同)

gho*_*g74 14

if test -e "$file_name";then
 ...
fi

if grep -q "poet" $file_name; then
  ..
fi
Run Code Online (Sandbox Code Playgroud)


Ste*_*eet 6

test -e将测试文件是否存在.如果测试成功,则test命令返回零值,否则返回1.

测试可以写成test -e或使用[]

[ -e "$file_name" ] && grep "poet" $file_name
Run Code Online (Sandbox Code Playgroud)

除非您确实需要grep的输出,否则可以测试返回值,因为如果没有匹配则grep将返回1,如果有匹配则返回0.

一般而言,您可以测试字符串是否为非空[ "string" ],如果非空,则返回0,如果为空则返回1