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?
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.
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 .
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).
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
if test -e "$file_name";then ... fi if grep -q "poet" $file_name; then .. fi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With