Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run current bash script in background

Tags:

bash

Usually I add "&" character to start my process in backgroud, exemple :

user@pc:~$ my_script &

But how can I make it in background without "&" character ?

#!/bin/bash

#What can I add here to hide current process ($$) and to release focus ?

start_server()
{   
    #my script here with infinite loop ...
}

Thanks guys.

like image 484
M. LAKHDARI Avatar asked Oct 20 '22 05:10

M. LAKHDARI


1 Answers

#!/bin/bash

if [[ "$1" != "--nodaemon" ]]; then
    ( "$0" --nodaemon "$@" </dev/null &>/dev/null & )
else
    shift
fi

#...rest of script

What this does is check to see if its first argument is "--nodaemon", and if so fire itself ("$0") off in the background with the argument "--nodaemon", which'll prevent it from trying to re-background itself in a sort of infinite loop.

Note that putting this as the first thing in the script will make it always run itself in the background. If it only needs to drop into the background under certain conditions (e.g. when run with the argument "start"), you'd have to adjust this accordingly. Maybe something like this:

#!/bin/bash

start_server()
{   
    #my script here with infinite loop ...
}

if [[ "$1" = "start" ]]; then
    ( "$0" start-nodaemon </dev/null &>/dev/null & )
elif [[ "$1" = "start-nodaemon" ]]; then
    start_server
elif #.....
like image 140
Gordon Davisson Avatar answered Jan 04 '23 05:01

Gordon Davisson