1

I have the following line in my unix script file:

if [[ -f $DIR1/$FILE1 ] -a [ -f $DIR1/$FILE2 ]]; then

As clear the line checks for existence of two files in a directory and if both the files are present, some logic will be executed.

However, on running the script I am getting the following error on above line:

test_script: line 30: syntax error at line 54: `]' unexpected

line 54 is where above line is present.

What does this error mean ? Where am I wrong ?

Thanks for reading!

5 Answers 5

1

For the most common shells at least, [] are not like parentheses in C where you use then to group subexpressions.

What you need is something like (for bash):

if [[ -f $DIR1/$FILE1 && -f $DIR1/$FILE2 ]]; then

If you want help with a specific (non-bash) shell, you should let us know which one you're using.

Sign up to request clarification or add additional context in comments.

Comments

1

There is no need of [] with -f.

if [ -f $DIR1/$FILE1 -a -f $DIR1/$FILE2 ]; then

Output:

shadyabhi@archlinux /tmp $ touch foo;touch foo2
shadyabhi@archlinux /tmp $ if [ -f "foo"  -a -f "foo2" ]; then echo "Hello"; fi
Hello
shadyabhi@archlinux /tmp $

Comments

1

It's interesting that there are multiple answers explaining the subtle differences between [ and [[, but for some reason our culture seems to discourage people from providing the obvious solution. Stop using '[' entirely. Instead of '[', use test:

if test -f $DIR1/$FILE1 && test -f $DIR1/$FILE2; then

Test is cleaner syntax than '[', which requires a final ']' argument and continually confuses people into thinking that the brackets are part of the language. '[[' is not portable and confuses people who don't realize that many shells provide extra functionality that is non-standard. There is a case to be made that [[ can be more efficient than [, but if run-time performance is a problem in your shell, you probably shouldn't be solving the problem in sh.

Comments

0

You had extra [ and ]

if [ -f $DIR1/$FILE1 -a -f $DIR1/$FILE2 ]; then

Basically, you were mixing two syntax that aim to do the same thing: namely [ ] and [[ ]]. The former is more portable but the latter is more powerful; although the majority of shells you would come across do support [[ ]].

But better still is the following since you are already using the [[ ]] construct

if [[ -f $DIR1/$FILE1 && -f $DIR1/$FILE2 ]]; then

Comments

0

As @paxdiablo stated, you can use it this way:

if  -f $DIR1/$FILE1 && -f $DIR1/$FILE2 ; then

or you can use it this way:

if -f $DIR1/$FILE || -f $DIR1/$FILE2 ;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.