1

Can anyone please help, I have an if statement in my Bash code that goes as is:

if [[ $1 == *.txt ]]; then
  echo "It's a TXT file!!!"
fi

I set the shell code to executable by adding #!/bin/sh, and doing chmod u+x main.sh, but it still prints out the error:

./main.sh: 3: [[: not found

Any help is appreciated!

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
1BL1ZZARD
  • 225
  • 2
  • 14
  • This might help: `sh` ([Bourne-shell](https://en.wikipedia.org/wiki/Bourne_shell)) is usally not `bash` ([Bourne-again shell](https://en.wikipedia.org/wiki/Bash_(Unix_shell))). – Cyrus Mar 16 '22 at 22:59
  • `[[` is not part of "if" syntax even in bash; `[[` is its own command, which can be used without needing `if` at all. – Charles Duffy Mar 16 '22 at 23:03

2 Answers2

4

[[ is a non-portable bashism and your shell (if it is bash) is not running as bash, but was likely invoked as /bin/sh or somehow forgot what [[ is.

The way to test for this in the fully posixly portable way:

case $1 in
(*.txt) echo "It's a TXT file.";;
(*)     echo "You've got to be kidding me!";;
esac
Jens
  • 69,818
  • 15
  • 125
  • 179
  • is there a way to run a function/if statement on the line '(*.txt) echo "It's a TXT file.";;'? – 1BL1ZZARD Mar 16 '22 at 23:03
  • 1
    @1BL1ZZARD, `echo` _is_ a statement; you can replace it with any other valid statement, including calling a function you defined. – Charles Duffy Mar 16 '22 at 23:04
2

[[ doesn't exist in sh, you need #!/bin/bash in the shebang line instead.

choroba
  • 231,213
  • 25
  • 204
  • 289