Home > Software engineering >  How to defer a function execution in bash?
How to defer a function execution in bash?

Time:09-22

I would like to defer a function execution. My current approach is something like this:

do_afterwards () {
    sleep 2
    echo "do something later"
}

do_afterwards &
start_my_webserver & start_monitoring_webserver

start_my_webserver & start_monitoring_webserver will run in the foreground of my terminal and "block it". I want to run do_afterwards after my Webservers started. Currently I am doing that simply with a dummy wait. How can I do this smarter?

CodePudding user response:

If the question is how to start both do_afterwards and start_monitoring_webserver simultaneously after start_my_webserver finished, then the following could work:

do_afterwards () {
    echo "do something later"
}

start_my_webserver () {
  echo "starting"
  sleep 2
  echo "started"
}

start_monitoring_webserver () {
  echo "monitoring"
  sleep 2
  echo "monitoring"
  sleep 2
  echo "monitoring"
}

post_start() {
  do_afterwards &
  start_monitoring_webserver
}

start_my_webserver && post_start

Result:

starting
started
monitoring
do something later
monitoring
monitoring
  •  Tags:  
  • bash
  • Related