【问题标题】:Strange issue relating to shell script files与 shell 脚本文件有关的奇怪问题
【发布时间】:2015-02-07 18:03:18
【问题描述】:

我在一个名为 restart_server.sh 的文件中有这个 shell 脚本:

echo "KILLING SERVER SESSION"
kill $(cat serverlastpid.txt)
sleep 20
echo "STARTING SERVER..."
java -jar eu.greensmartcampus-0.0.1-SNAPSHOT-jar-with-dependencies.jar </dev/null>/dev/null 2>&1 &
echo $! > serverlastpid.txt
echo "SERVER STARTED! PID:" $(cat serverlastpid.txt)

如果我单独执行每一行,我会得到:

root@production:/opt/AppServer# echo "KILLING SERVER SESSION"
KILLING SERVER SESSION
root@production:/opt/AppServer# kill $(cat serverlastpid.txt)
root@production:/opt/AppServer# sleep 20
root@production:/opt/AppServer# echo "STARTING SERVER..."
STARTING SERVER...
root@production:/opt/AppServer# java -jar eu.greensmartcampus-0.0.1-SNAPSHOT-jar-with-dependencies.jar </dev/null>/dev/null 2>&1 &
[1] 14620
root@production:/opt/AppServer# echo $! > serverlastpid.txt
root@production:/opt/AppServer# echo "SERVER STARTED! PID:" $(cat serverlastpid.txt)
SERVER STARTED! PID: 14620
root@production:/opt/AppServer#

现在,如果我只是在一个 shell 脚本文件中运行所有这些行,我会得到这个输出:

root@production:/opt/AppServer# sh restart_server.sh
restart_server.sh: 1: restart_server.sh: echo: not found
STARTING SERVER...
SERVER STARTED! PID: 14777
[1]+  Exit 143                java -jar eu.greensmartcampus-0.0.1-SNAPSHOT-jar-with-dependencies.jar < /dev/null > /dev/null 2>&1
root@production:/opt/AppServer#

一些 echo 消息丢失并且屏幕上出现一些错误。

为什么会这样?与单独运行每一行或在 .sh 文件中运行有何不同?

编辑:添加 #!/bin/bash 作为第一行输出:

root@production:/opt/AppServer# sh restart_server.sh
restart_server.sh: 1: restart_server.sh: #!/bin/bash: not found
KILLING SERVER SESSION
STARTING SERVER...
SERVER STARTED! PID: 15366
root@production:/opt/AppServer#

【问题讨论】:

  • 脚本的第一行是什么?你用的是什么外壳?
  • 我猜。第一行是echo "KILLING SERVER SESSION"
  • 考虑制作第一行 #!/bin/bash...
  • 他一直在抱怨第一行,现在是#!/bin/bash。 (检查我在 OP 中的编辑,因为 cmets 不能有换行符)。
  • 呃。这是什么操作系统?大约二十年来,我还没有遇到过一个没有 /bin/bash 的 Linux 发行版......

标签: linux bash shell unix sh


【解决方案1】:

查看chat中的讨论。

问题出在以 UTF-8 编码为字节 0xEF 0xBB 0xBF 的 Unicode 字节顺序标记 (BOM) 上,这是 shell 不喜欢的。删除它,并确保 shell 代码与 dash 而不是 bash 一起工作,让事情正常工作。

诊断的关键步骤是:

  • 确定 shell 是 dash 而不是 bash
  • 使用十六进制转储工具检查文件的前几行,以便 BOM 可见。
  • 知道如何去掉 BOM(它后面跟着一个换行符,所以sed 可以很容易地使用)。
  • 使用sh -x restart_server.sh 查看正在执行的内容。

【讨论】:

    【解决方案2】:

    你需要调用 bash 来执行一个 bash 脚本,这样做使用

    whereis bash
    

    那么你应该在 bash 脚本的 第一行 中放入给定的路径

    #!/bin/bash

    有时是#!/bin/sh

    这取决于你的发行版

    【讨论】:

      猜你喜欢
      • 2019-04-27
      • 2017-10-23
      • 1970-01-01
      • 2010-09-12
      • 1970-01-01
      • 2021-08-27
      • 2017-05-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多