views:

255

answers:

4

hello, Is it possible to have multiple unary operators in if statements.. Here is the code snippet which is giving me error.

Please correct the code here.

if [ -f $input_file ] -a [ -f $output_file ] -a [ -f $log_file ] ]
then
### Some Code here
fi

Thanks Kiran

+4  A: 
if [ -f "file1" -a -f "file2" -a "file3" ]; then
   #some code
fi
ghostdog74
It works like a Magic.. thanks for the quick response..
Kiran
+1  A: 

[ is a command, not part of the if statement. As such you should pass it each of the appropriate arguments instead of trying to incorrectly run it as you have.

if [ arg1 arg2 arg3 arg4 ... ]
then
Ignacio Vazquez-Abrams
In Cygwin environments, there is a C:\cygwin\bin\[.exe. Really strange feeling to take a look at this folder for the first time.
Boldewyn
+2  A: 

You can see the [ ... ] operator only as a shortcut for test .... The options are used th same way.

So in your case you could either write the ghostdog74 way or :

if [ -f $input_file ] && [ -f $output_file ] && [ -f $log_file ]
then
### Some Code here
fi
gregseth
+1  A: 

If you use Bash's double-bracket, you can do this:

if [[ -f "$input_file" && -f "$output_file" && -f "$log_file" ]]

which I find cleaner to read than other options shown here (but that's subjective). However, it has other advantages.

And, as ghostdog74 shows, you should always quote variables containing filenames.

Dennis Williamson