nohup, with stdout/stderr in a specific file

Posted on

nohup is a useful tool, but it has a inconvenient : all output goes to a nohup.out, in current directory.

Here a bash script with features :

  • redirect output to a specific file , in /tmp directory.
  • kill process which have same name/parameter, if running
  • run the command in session leader , background, detached (setsid/ bg /disown)
#!/bin/bash
 args=$*
 [ -z "$args" ] && echo "no  command! " && exit 1
 [[ $(pgrep -laf "$args" | wc -l) > 2 ]]  && echo "kill old $args" && pkill -f "${args}" 
 short=$(echo $args | ruby -ne 'print $_.gsub(/[^\w_-]/,"").gsub(/+/,"_")')
 echo Run $args …
 echo output to : /tmp/rnohup-$$-$short.log 
 setsid $* &>/tmp/rnohup-$$-$short.log </dev/null  &
 disown
 sleep 1
 echo "Running :"
 pgrep -laf "$args" 

Leave a comment