Home > Software design >  Unix scripting to find a text file is not working
Unix scripting to find a text file is not working

Time:10-03

I need to write a Unix Shell script in such a way if .txt files exists in the path, it should return 0. If some other files exists it should return 1

I tried the below script but it is not working..

#!/bin/sh
cd /shz/abc_test/test/test_add/SourceFiles/test1/test01/test02/
chk_files()
{
if [ -e *.txt ]; then
      echo "File Exists" 
      return 0
      exit
else
      echo "File doesn't exists" 
      return 1
      exit
fi
return
}

CodePudding user response:

has_text_files()
{
  for f in ./*.txt; do
    if [ -f "$f" ]; then
      return 0
    fi
  done
  return 1
}

The above code:

  • ignores directories that are named *.txt.
  • doesn't print anything, it only returns the status.
  • is extra careful about strange filenames, such as filenames starting with - or containing spaces.
  • Has a more appropriate function name has_text_files instead of the unspecific chk_files.

CodePudding user response:

Of course munch more advanced script can be developed. I see you are going to use simple way. So, you script fails when multiple files are exist. I updated function part and looks it is working.

chk_files()
{
ifExist=$(ls| grep ".txt$")      # check Files are exist, but no need to list and print.
if [ $? -eq 0 ]; then   # check return code of above command is success (0)
      echo "File Exists" 
      return 0
      exit
else
      echo "File doesn't exists" 
      return 1
      exit
fi
return
}
  • Related