Reputation: 1055
I'm writing a script that needs two input files. I wrote the following code:
if (( $# < 3 || ! ( -f $1 && -f $2 ) )); then
echo Cannot open input files
exit 1
fi
But if I supply only one input file, I get this error:
line 4: ((: 1 < 3 || ! ( -f tests/example && -f ) : missing `)' (error token is "tests/example && -f ) ")
I guess the OR evaluation isn't "lazy", so the -f $1
works because it's replaced by -f tests/example
, but -f $2
causes an error.
Is there some way to "force lazy evaluation" (if $# < 3
don't try to evaluate the rest) in the if
statement? Or should I be doing things differently?
Upvotes: 1
Views: 393
Reputation: 123608
I'm writing a script that needs two input files.
Why are you checking if the number of arguments is less than 3
in order to exit? You need to ensure that there are no fewer than 2
arguments. Use short-circuting for all the checks. Say:
if [[ $# < 2 || ! -f "$1" || ! -f "$2" ]]; then
echo Cannot open input files
exit 1
fi
Actually, even the following would suffice for your question:
if [[ ! -f "$1" || ! -f "$2" ]]; then
echo Cannot open input files
exit 1
fi
Upvotes: 3
Reputation: 785856
(( ... ))
is for maths operations in shell.
Rewrite your if condition like this:
[[ $# < 3 || ! ( -f "$1" && -f "$2" ) ]]
Upvotes: 2