Last active
October 18, 2020 11:35
-
-
Save LukeSavefrogs/47f0d49170584b42f2d6c62950aac963 to your computer and use it in GitHub Desktop.
This gist shows an interesting use i've found of background processes and `wait` keyword. I spawn two processes with different duration and then wait for them to finish. The 2 processes run simultaneously and the script finishes once both have finished. It can be useful when you have to deal with long-running processes and want to optimize the t…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# -------------------------------------------- | |
# Here we could define our GLOBAL variables. | |
# Using `declare -r` makes the variable read-only (just like a constant in other languages) | |
# -------------------------------------------- | |
declare -r BOLD='\033[1m'; | |
declare -r NORMAL='\033[0m'; | |
# -------------------------------------------- | |
# This will be the entry point of the script. | |
# | |
# This kind of C-like structure allows to define the main code block BEFORE everything else, so that code is more visible and clear | |
# -------------------------------------------- | |
main () { | |
# I use 'printf' over echo because it gives me more control over what can i display. | |
# Passing variables/commands as parameters automatically escapes them | |
printf "${BOLD}[%s] START test...${NORMAL}\n\n" "$(date +'%H:%M:%S')"; | |
time test | |
printf "\n"; | |
printf "${BOLD}[%s] END test...${NORMAL}\n\n" "$(date +'%H:%M:%S')"; | |
return 0; | |
} | |
# -------------------------------------------- | |
# Every other function definition goes here | |
# -------------------------------------------- | |
function test () { | |
printf "[%s] Starting first process (10 sec duration)...\n" "$(date +'%H:%M:%S')"; | |
sleep 10 & | |
printf "[%s] Starting second process (8 sec duration), now in a sub-shell...\n" "$(date +'%H:%M:%S')"; | |
(sleep 8) & | |
printf "[%s] Waiting for all the processes to finish their execution\n\n" "$(date +'%H:%M:%S')"; | |
wait | |
printf "[%s] All child processes has finished execution\n" "$(date +'%H:%M:%S')"; | |
} | |
# THIS executes the main function. It is placed at the end so that at the time of execution everything is already defined | |
main "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment