shell脚本执行异常和报错解决

235 阅读1分钟

shell脚本执行异常和报错解决

shell脚本执行异常和报错解决,通常有以下几点:

  • shell脚本执行失败,手动执行成功
  • 执行脚本报错

shell脚本执行失败,手动执行成功

脚本如下

# cat /usr/local/restart.sh
#!/bin/bash

pid=`ps -ef | grep read-cookie-0.0.1-SNAPSHOT.jar | grep -v grep |awk '{print $2}'`
if [ $pid ]; then
    echo :service is stop pid=$pid
    kill -9 $pid
fi

nohup java -jar -Xms1024m -Xmx1024m -jar /usr/local/read-cookie-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod &

pid=`ps -ef | grep read-cookie-0.0.1-SNAPSHOT.jar | grep -v grep |awk '{print $2}'`
if [ $pid ]; then
    echo :service is running pid=$pid
fi


# cat master-read-cookie.sh
#!/bin/bash
. /etc/rc.d/init.d/functions
\cp /usr/local/read-cookie-0.0.1-SNAPSHOT.jar{,.bak}
\cp -f read-cookie-0.0.1-SNAPSHOT.jar /usr/local/

bash /usr/local/restart.sh
ps -ef |grep read-cookie |grep -v grep  && action '服务启动成功'


#bash  master-read-cookie.sh

 

报错一:nohup: failed to run command 'java': No such file or directory

执行如下命令报错,并且服务启动失败
#nohup java -jar -Xms1024m -Xmx1024m -jar /usr/local/read-cookie-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod &
nohup: appending output to 'nohup.out'
nohup: failed to run command 'java': No such file or directory

解决方法

rm -rf /usr/bin/{javac,jar,java} 
ln -sv /usr/local/jdk1.8/bin/javac /usr/bin/ 
ln -sv /usr/local/jdk1.8/bin/java /usr/bin/
ln -sv /usr/local/jdk1.8/bin/jar /usr/bin/

 

报错二: Error: Unable to access jarfile service-monitor-0.0.1-SNAPSHOT.jar

非交互式执行失败
# sshpass -p 123456 ssh -o StrictHostKeyChecking=no 10.0.0.88 'bash /usr/local/restart.sh'
:service is stop pid=25373
Error: Unable to access jarfile service-monitor-0.0.1-SNAPSHOT.jar

手动执行依然失败
# bash /usr/local/restart.sh
nohup: appending output to ‘nohup.out’
# ps -ef |grep java
root     25459 25431  0 23:19 pts/0    00:00:00 grep --color=auto java


# cd /usr/local/
# bash restart.sh
nohup: appending output to ‘nohup.out’
:service is running pid=25471

解决方法: 指定绝对路径

# cat restart.sh
#!/bin/bash
pid=`ps -ef | grep service-monitor-0.0.1-SNAPSHOT.jar | grep -v grep |awk '{print $2}'`

if [ $pid ]; then
    echo :service is stop pid=$pid
    kill -9 $pid
fi

nohup java -jar -Xms1024m -Xmx1024m -jar /usr/local/service-monitor-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod &

pid=`ps -ef | grep service-monitor-0.0.1-SNAPSHOT.jar | grep -v grep |awk '{print $2}'`

if [ $pid ]; then
    echo :service is running pid=$pid
fi

sshpass -p 123456 ssh -o StrictHostKeyChecking=no 10.0.0.88 'bash /usr/local/restart.sh'

:service is stop pid=25471

. ____ _ __ _ _
/\ / ' __ _ () __ __ _ \ \ \ \
( ( )_
_ | '_ | '| | ' / ` | \ \ \ \
\/ __)| |)| | | | | || (
| | ) ) ) )
' || .__|| ||| |_, | / / / /
=========|
|==============|
/=////
:: Spring Boot :: (v2.6.6)