Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if file exists and whether it contains a specific string

Tags:

shell

ksh

I want to check if file2.sh exists and also if a specific word, poet is part of the file. I use grep to create the variable used_var.

#!/bin/ksh  file_name=/home/file2.sh                   used_var=`grep "poet" $file_name`     

How can I check if used_var has some value?

like image 358
randeepsp Avatar asked Sep 22 '10 07:09

randeepsp


People also ask

How do you check if a file contains a specific string?

Just run the command directly. Add -q option when you don't need the string displayed when it was found. The grep command returns 0 or 1 in the exit code depending on the result of search.

How do I check to see if a file exists?

To check if a file exists, you pass the file path to the exists() function from the os. path standard library. If the file exists, the exists() function returns True . Otherwise, it returns False .

Which of the following option is used to check whether the entered input is a file or not?

While checking if a file exists, the most commonly used file operators are -e and -f. The '-e' option is used to check whether a file exists regardless of the type, while the '-f' option is used to return true value only if the file is a regular file (not a directory or a device).


2 Answers

Instead of storing the output of grep in a variable and then checking whether the variable is empty, you can do this:

if grep -q "poet" $file_name then     echo "poet was found in $file_name" fi 

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

Here are some commonly used tests:

   -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 

Example:

if [ -e "$file_name" ] && [ ! -z "$used_var" ] then     echo "$file_name exists and $used_var is not empty" fi 
like image 125
dogbane Avatar answered Sep 20 '22 11:09

dogbane


if test -e "$file_name";then  ... fi  if grep -q "poet" $file_name; then   .. fi 
like image 35
ghostdog74 Avatar answered Sep 19 '22 11:09

ghostdog74