无法在bash中添加其他脚本

时间:2016-12-22 13:04:35

标签: bash scripting

我写了一个bash脚本,它调用同一个文件夹中的另一个脚本。我只需将./email_pacotes.sh放在主脚本

中即可
#awk '{print $2}' >> /tmp/lista_pacotes.log adiciona resultado ao arquivo /tmp/tmp_pacotes_adicionados.log
echo "\nPacotes adicionados até" $(date) "\n" >> /tmp/tmp_pacotes_adicionados.log

cat /tmp/diferencas.log >> /tmp/tmp_pacotes_adicionados.log

./email_pacotes.sh

#adiciona resultados anteriores
cat /tmp/pacotes_adicionados.log >> /tmp/tmp_pacotes_adicionados.log

我认为它工作正常,但由于其他原因我不得不调试脚本,我发现第一次运行主脚本时没有添加第二个脚本。

我收到以下消息:

[...]
./email_pacotes.sh: 17: ./email_pacotes.sh: [[: not found
./email_pacotes.sh: 17: ./email_pacotes.sh: [[: not found
./email_pacotes.sh: 17: ./email_pacotes.sh: [[: not found
./email_pacotes.sh: 17: ./email_pacotes.sh: [[: not found
./email_pacotes.sh: 17: ./email_pacotes.sh: [[: not found
[...]

当我第一次将脚本放入文件夹时运行脚本时会发生这种情况。如果我再次运行它,消息不再显示,所以我猜它不是语法问题。我也认为可能是具有权限的东西,但我将两个脚本都更改为0777并且消息仍然存在。

这是正常行为吗?可能导致这种情况的原因是什么?

Obs1:我正在使用-x选项调试主脚本。

Obs2:我现在又做了一次测试。它不断抛出相同的消息,但在某些时候它最终会调用脚本。那么也许只是找到文件或抛出异常的时候了?

1 个答案:

答案 0 :(得分:1)

从错误中,我非常确定您使用除bash之外的shell运行第二个脚本。 bash(以及zsh和其他一些shell)支持[[ ]]条件,但不是标准的,还有其他shell不支持它。因此,如果您想使用该(或任何其他非标准bash功能),您需要在该脚本中使用正确的shebang行。通常,这意味着您需要使用#!/bin/bash(或#!/usr/bin/env bash}, #!/bin/sh启动脚本。

不过,还有另外一件令我担心的事情。使用./email_pacotes.sh运行第二个脚本将在当前工作目录中查找它,该目录继承自运行第一个脚本的进程,并且几乎可以在任何地方运行。如果您希望它在第一个脚本所在的同一目录中查找第二个脚本,最好的方法是找到第一个脚本,例如"$(dirname "$BASH_SOURCE")"(并猜测 - BASH_SOURCE是什么仅限bash功能,因此也可以使用bash shebang启动第一个脚本。然后,您可以通过显式路径引用第二个脚本(以及任何其他相关文件):

#!/bin/bash
...
scriptDir="$(dirname "$BASH_SOURCE")"
if [[ ! -d "$scriptDir" ]]; then
    echo "Something's terribly wrong; I can't find myself!" >&2
    exit 1
fi
...
"$scriptDir/email_pacotes.sh"

或将脚本cd放到其自己的目录中,然后使用相对路径:

#!/bin/bash
...
cd "$(dirname "$BASH_SOURCE")" || {
    echo "Something's terribly wrong; I can't cd to my own directory!" >&2
    exit 1
}
...
./email_pacotes.sh

我更喜欢第一种方法,因为如果任何脚本接受路径(例如作为参数),用户将期望这些路径相对于用户在运行脚本时的位置进行解释,而不是相对于脚本本身是;脚本中的cd会破坏这一点。

相关问题