I have the following new line in my .sh file

su --session-command='$javaCommandLine & >>$serviceLogFile 2>&1 & echo \$! >$pidFile' $serviceUser || return 1

When I had it with double quotes it somewhat worked but the pidFile had the wrong pid it was off by one. The solution from research was to use single quotes and I can't get single quotes to work.

I get now 2 errors

bash: $pidFile: ambiguous redirect
bash: $serviceLogFile: ambiguous redirect

Seems I can't use variables or output to variables in single quotes?

This line almost works but the pid is off by one
This code below would start from boot up but the pid is wrong.

su --session-command="$javaCommandLine & >>$serviceLogFile 2>&1 & echo \$! >$pidFile" $serviceUser || return 1

which had to replace this buggy old 2 line code.

cmd="nohup $javaCommandLine >>$serviceLogFile 2>&1 & echo \$! >$pidFile"
# Don't forget to add -H so the HOME environment variable will be set correctly.
sudo -u $serviceUser -H $SHELL -c "$cmd" || return 1

Old code worked fine but it couldn't be started from boot up.


The process ID is off by one because you have put an extra & after the $javaCommandLine. In other words, you have put two processes in the background before calling echo $!, thus getting the PID of >>$serviceLogFile 2>&1 rather than $javaCommandLine. Those two pieces should be put in one, as the old 2 line codes shows

 su --session-command="$javaCommandLine & >>$serviceLogFile 2>&1 & echo \$! >$pidFile" $serviceUser || return 1

You might need to change it to -

 su --session-command="$javaCommandLine >>$serviceLogFile 2>&1 & echo \$! >$pidFile" $serviceUser || return 1
| improve this answer | |
  • omg so simple and I was struggling looking all over the place for a solution! TYVM – SSpoke Dec 23 '13 at 6:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.