3

In a (ba)sh script, how do I ignore file-not-found errors?

I am writing a script that reads a (partial) filename from stdin, using:

read file; $FILEDIR/$file.sh

I need to give the script functionality to reject filenames that don't exist.

e.g.

$UTILDIR does NOT contains script.sh User types script
Script tries to access $UTILDIR/script.sh and fails as

./run.sh: line 32: /utiltest/script.sh: No such file or directory

How do I make the script print an error, but continue the script without printing the 'normal' error?

je4d
  • 7,628
  • 32
  • 46
Nathan Ringo
  • 973
  • 2
  • 10
  • 30

4 Answers4

2
if [ -e $FILEDIR/$file.sh ]; then
 echo file exists;
else
 echo file does not exist;
fi
gogaman
  • 430
  • 3
  • 5
2

You can test whether the file exists using the code in @gogaman's answer, but you are probably more interested in knowing whether the file is present and executable. For that, you should use the -x test instead of -e

if [ -x "$FILEDIR/$file.sh" ]; then
   echo file exists
else
   echo file does not exist or is not executable
fi
je4d
  • 7,628
  • 32
  • 46
1

Here we can define a shell procedure that runs only if the file exists

run-if-present () {
  echo $1 is really there
}

[ -e $thefile ] && run-if-present $thefile
DigitalRoss
  • 143,651
  • 25
  • 248
  • 329
  • That introduces a race condition. – Philipp Apr 15 '12 at 01:02
  • @tikiking1: The file might be deleted between the test and the command, so it's possible that in `run-if-present` the file is actually not present. `run-if-present` still has to handle this case. – Philipp Apr 16 '12 at 18:50
1

Depending on what you do with the script, the command will fail with a specific exit code. If you are executing the script, the exit code can be 126 (permission denied) or 127 (file not found).

command
if (($? == 126 || $? == 127))
then
  echo 'Command not found or not executable' > /dev/stderr
fi
Philipp
  • 48,066
  • 12
  • 84
  • 109
  • This I appended (a modified version) that receives the utility's returns. While not being exactly what I was searching for this was helpful. – Nathan Ringo Apr 16 '12 at 03:20