【发布时间】: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 发行版......