I'm trying to write a script that has to check if a file exists. In the console I write

if [[ -a /path/to/file.txt ]]; then echo "not mod"; else echo "mod"; fi

and I get

not mod

but when I write a script to do the same thing:

#!/bin/sh
if [[ -a /path/to/file.txt ]]; then echo "not mod"; else echo "mod"; fi

and then execute the script, I get this:

./ex.sh: 2: [[: not found
mod

I saved the script on the current directory and named it ex.sh, then I made sure it is executable. To call the script I do this:

./ex.sh

Why am I getting this problem? I already tried many things:

if [ -a /home ...

and

if test -a /home ...

Both of them return

13: -a: unexpected operator
link|improve this question
I was able to make it work, but for that I had to remove the first line (#!/bin/sh) Do you know why this happens? – Buzu Jan 4 at 6:21
try #!/bin/bash – kev Jan 4 at 6:38
hello kev, I relized that too. I just updated my question. I spent too much time on this, but I'm glad I could solve it. Thanks for your answer. It is indeed, the solution to the problem. – Buzu Jan 4 at 6:43
@Kev Please post that as an answer – slhck Jan 4 at 8:42
Buzu, @Kev - if you find an answer, post it as an answer below, do not edit the question. – grawity Jan 4 at 8:43
show 1 more comment
feedback

1 Answer

You are running a script written for bash under sh, which lacks many of the extended syntax features – [[ is a bash builtin command and is not available in sh.

Change #!/bin/sh to #!/bin/bash or to #!/usr/bin/env bash.

link|improve this answer
On some systems, /bin/sh is a symlink to /bin/bash. And it's probably reasonably safe to assume that bash is /bin/bash. – Keith Thompson Jan 4 at 19:07
@Keith: It's /bin/bash on most Linux systems, but /usr/pkg/bin/bash on BSDs, or /usr/local/bin/bash if one compiles directly from source. – grawity Jan 4 at 19:35
@grawity: Or wherever else you decide to put it if you compile from source. Ok, good point. Personally, I'd rather edit the shebang for each system than use the /usr/bin/env hack (which uses whichever bash happens to be in the callers $PATH at the moment), but YMMV. (And you can make /bin/bash a symlink -- if you have admin rights and you don't mind messing with /bin.) – Keith Thompson Jan 4 at 21:36
@Keith: /usr/local is where autotools decides to put it by default. As far as "personally" goes, I like having several different servers and VMs pull from the same scripts/tools repository, and not needing to re-edit the shebangs on half of them after every commit. – grawity Jan 5 at 2:03
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.