Bash: How to check if certain files exist?

In a bash script, I have to check for multiple files.

I know an awkward way to do this, which means that my main program should be inside this ugly nested structure:

 if [ -f $FILE1 ] then if [ -f $FILE2 ] then echo OK # MAIN PROGRAM HERE fi fi 

The next version does not work:

 ([ -f $FILE1 ] && [ -f $FILE2 ]) || ( echo "NOT FOUND"; exit 1 ) echo OK 

He is typing

 NOT FOUND OK 

Is there an elegant way to do it right?

UPDATE: See accepted answer. Also, in terms of elegance, I like Jonathan Leffler's answer :

 arg0=$(basename $0 .sh) error() { echo "$arg0: $@ " 1>&2 exit 1 } [ -f $FILE2 ] || error "$FILE2 not found" [ -f $FILE1 ] || error "$FILE1 not found" 
+6
bash shell error-handling
source share
4 answers

What about

 if [[ ! ( -f $FILE1 && -f $FILE2 ) ]]; then echo NOT FOUND exit 1 fi # do stuff echo OK 

See help [[ and help test for parameters that can be used with style tests [[ . Also read this faq entry .

Your version does not work because (...) creates a new sub-shell in which exit is executed. This therefore only affects this subshell, but not the execution of the script.

Instead, work is performed that executes commands between {...} in the current shell.

It should also be noted that you need to specify both variables to make sure that there is no unwanted extension or word splitting (they should be passed as a single argument to [ ).

 [ -f "$FILE1" ] && [ -f "$FILE2" ] || { echo "NOT FOUND"; exit 1; } 
+10
source share

I think you are looking for:

 if [ -f $FILE1 -a -f $FILE2 ]; then echo OK fi 

See man test for more details on what you can put inside [ ] .

+4
source share

You can list the files and check them in a loop:

 file_list='file1 file2 wild*' for file in $file_list; do [ -f $file ] || exit done do_main_stuff 
+3
source share

I usually use the option:

 arg0=$(basename $0 .sh) error() { echo "$arg0: $@ " 1>&2 exit 1 } [ -f $FILE2 ] || error "$FILE2 not found" [ -f $FILE1 ] || error "$FILE1 not found" 

There is no particular advantage in that the shell of the script has a single exit point - it also does no harm, but fatal errors can also lead to the completion of the script.

The only subject of discussion will be the question of whether to diagnose as many problems as possible before exiting, or simply diagnose the first. On average, diagnosing only the first is much easier.

+1
source share

All Articles