Why do I Get [[: not found When Running a Script?

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
6

2 Answers

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.

5

Specify bash instead of sh when running the script. I personally noticed they are different under ubuntu 12.10:

bash script.sh arg0 ... argn

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like