Run current bash script in background

前端 未结 1 1292
攒了一身酷
攒了一身酷 2020-12-19 11:43

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

user@pc:~$ my_script &

But how can I make it in backgroun

相关标签:
1条回答
  • 2020-12-19 12:29
    #!/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 #.....
    
    0 讨论(0)
提交回复
热议问题