1

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?

4

4 に答える 4

2
if [ -e $FILEDIR/$file.sh ]; then
 echo file exists;
else
 echo file does not exist;
fi
于 2012-04-15T00:48:03.517 に答える
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
于 2012-04-15T00:55:02.120 に答える
1

スクリプトで何をするかに応じて、コマンドは特定の終了コードで失敗します。スクリプトを実行している場合、終了コードは126(許可が拒否されました)または127(ファイルが見つかりません)になります。

command
if (($? == 126 || $? == 127))
then
  echo 'Command not found or not executable' > /dev/stderr
fi
于 2012-04-15T01:19:00.990 に答える
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
于 2012-04-15T00:57:42.333 に答える