A Simple BASH Function/Script to Run a Command in Background


If you connect to a SSH – when the window is closed, all running programs in the current session will be terminated. One way to solve this is to run the command in screen session. The following uses “nohup” to define a function bkr() and you can run the script easily to start a problem in background – which is free from termination even if you terminate the current SSH session:

We define a bkr() function that uses nohup to take whatever parameters ($@) and redirect all output and errors to /dev/null device. And then we check if parameters (command to stay in background) exist using -z $1 check. Then we call the BASH function with all parameters supplied.

1
2
3
4
5
6
7
8
9
10
11
12
#!/bin/bash
 
bkr() {
    (nohup "$@" &>/dev/null 2>&1 &)
}
 
if [[ -z $1 ]]; then
    echo Usage $0 command
    exit 1
fi
 
bkr $@
#!/bin/bash

bkr() {
    (nohup "$@" &>/dev/null 2>&1 &)
}

if [[ -z $1 ]]; then
    echo Usage $0 command
    exit 1
fi

bkr $@

One example:

1
$ bkr yes
$ bkr yes

See also: Three ways of Running a continuous NodeJS Application on Your Server

BASH Programming/Shell

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
252 words
Last Post: Teaching Kids Programming - Depth First Search Algorithm to Delete Even Leaves Recursively From Binary Tree
Next Post: Teaching Kids Programming - Flip One Digit via Greedy Algorithm

The Permanent URL is: A Simple BASH Function/Script to Run a Command in Background

Leave a Reply