A script like the following:
#!/bin/bash
function hello {
echo "Hello World"
}
hello
will work fine but when I call it with nohup
nohup ./myScript.sh
the script no longer works and the following is printed:
./myScript.sh: 5: ./myScript.sh: function: not found
Hello World
./myScript.sh: 9: ./myScript.sh: Syntax error: "}" unexpected
I know that there is no point in using nohup
for this script since it runs fairly quick but I have another script that is going to take several hours to run and I have used that function syntax in it. Is there a way to fix this?
Note that to declare a function in POSIX standard shell, you just write the function name followed by a pair of empty parentheses, and a body in curly brackets:
#!/bin/bash
hello() {
echo "Hello World"
}
hello
Some shells, like bash, also accept the function
keyword to declare functions, but based on your error message, it looks like the shell that you are using does not accept it. For portability, it would be best to use the POSIX standard declaration style.
The reason you see the difference between running the script directly and running the script under nohup
is the blank lines at the beginning of the file. The #!
need to be the first two characters of the file in order to specify the interpreter, otherwise that is just a comment. It looks like when executed from within a Bash shell, the script gets interpreted by Bash and it recognizes the Bash extension. But when run from nohup
, it gets interpreted by sh
, which on some systems is a more bare-bones shell like dash
that only supports the POSIX syntax above.