Linux: [[: not found

Автор: | 17/02/2017

Во время Jenkins-билда – скрипт деплоя возвращает ошибку:

...
[jm-cms-transform-layer-build] Running shell script
+ [[ -d config ]]
/var/jenkins_home/workspace/jm-cms-transform-layer-build@tmp/durable-6569c8ce/script.sh: 2: /var/jenkins_home/workspace/jm-cms-transform-layer-build@tmp/durable-6569c8ce/script.sh: [[: not found
...

Причина в том, что Jenkins использует во время билда sh (docker.image('node')), а не bash, а sh не поддерживает многие возможности bash:

[simterm]

root@jm-webapp-ci-temp:/tmp# sh
# [[ -e filename ]] || echo $?
sh: 1: [[: not found
127
# bash
root@jm-webapp-ci-temp:/tmp# [[ -e filename ]] || echo $?
1

[/simterm]

Поэтому, вместо проверки через [[...]] – используем test:

[simterm]

# test -e filenmae || echo $?
1

[/simterm]

И немного проверки:

[simterm]

root@jm-webapp-ci-temp:/tmp# type -a [[
[[ is a shell keyword
root@jm-webapp-ci-temp:/tmp# type -a [
[ is a shell builtin
[ is /usr/bin/[
root@jm-webapp-ci-temp:/tmp# type -a test
test is a shell builtin
test is /usr/bin/test

[/simterm]

Видим, что [[ – это shell keyword:

[simterm]

# type -a [[
[[ is a shell keyword

[/simterm]

И смотрим man:

[simterm]

root@jm-webapp-ci-temp:/tmp# man 1 bash | grep "\[\["
       ! case  coproc  do done elif else esac fi for function if in select then until while { } time [[ ]]
       [[ expression ]]
              expansion  are  not  performed  on  the words between the [[ and ]]; tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution, process substitution, and quote removal are performed.
              When used with [[, the < and > operators sort lexicographically using the current locale.
              ...

[/simterm]