Fully-Faltoo blog by Pratyush

Bio Twitter Screener

26th June 2025

Using bgrun to run a command in background

Yesterday I wrote a script to create backups for my server. Just when I ran the script, I realised it would take an hour to complete.

It was 7pm. I needed to leave for home.

I cursed myself for not doing bgrun bash backup.sh instead of bash backup.sh.

The thing is bgrun doesn’t exist.

The closest thing I found was:
nohup your_command > output.log 2>&1 & disown.

Let’s break it down:

  • nohup = no hangup
  • your_command = anything like bash backup.sh
  • > output.log = put the output of the command in output.log
  • 2>&1 = send errors too in output.log
  • & = run the command in background
  • disown = disown the task so that ctrl+c doesn’t kill it

nohup works – but has too many moving parts. It is too hard to remember the whole command when the need arises.

So I co-paired with GPT to create an easy-to-remember alias for it.

bgrun() {
    # run the script in background
    local logfile="output.log"
    nohup "$@" > "$logfile" 2>&1 &
    local pid=$!          # $! is the id of the last job run in background
    disown "$pid"     # ctrl+c shouldn't kill the script
    echo "Started: $* (log: $logfile)"
    echo "Check status: ps -ef | grep $pid"
    echo "Kill task: kill $pid"
    echo "View log: tail -f output.log"
}

I added the above in ~/.bashrc, did source ~/.bashrc and had the bgrun command available.

Before going to sleep, I did bgrun bash backup.sh and exited the shell. The first thing in the morning was to login into the server and run tail -f output.log.


Comments