使用nohup调用时,为什么以下bash脚本无法正常工作?

Luc*_*nis 3 bash shell nohup

像下面这样的脚本:

#!/bin/bash

function hello {

        echo "Hello World"

}

hello
Run Code Online (Sandbox Code Playgroud)

会工作正常,但当我用nohup称呼它

nohup ./myScript.sh 
Run Code Online (Sandbox Code Playgroud)

该脚本不再有效,并打印以下内容:

./myScript.sh: 5: ./myScript.sh: function: not found
Hello World
./myScript.sh: 9: ./myScript.sh: Syntax error: "}" unexpected
Run Code Online (Sandbox Code Playgroud)

我知道使用nohup这个脚本是没有意义的,因为它运行得相当快,但我有另一个脚本需要几个小时才能运行,我已经在其中使用了该函数语法.有没有办法来解决这个问题?

Bri*_*ell 5

注意,要在POSIX标准shell中声明一个函数,只需编写函数名称,后跟一对空括号,以及大括号中的正文:

#!/bin/bash

hello() {
    echo "Hello World"
}

hello
Run Code Online (Sandbox Code Playgroud)

有些shell(如bash)也接受function关键字来声明函数,但根据您的错误消息,它看起来像您正在使用的shell不接受它.为了便于携带,最好使用POSIX标准声明样式.

您看到直接运行脚本和运行脚本之间的区别的原因nohup是文件开头的空白行.的#!需要是文件的前两个字符,以指定的解释,否则这只是一个评论.看起来当从Bash shell中执行时,脚本会被Bash解释并识别Bash扩展.但是当nohup它运行时,它会被解释sh,在某些系统上是一个更简单的shell,就像dash只支持上面的POSIX语法一样.