Asynchronous Shell Commands

Asynchronous shell commands

You can just run the script in the background:

$ myscript &

Note that this is different from putting the & inside your script, which probably won't do what you want.

How to make asynchronous function calls in shell scripts

Something to experiment with:

delayed_ajax() {
local url=$1
local callback=$2
local seconds=$3

sleep $seconds
curl -s "$url" | "$callback"
}

my_handler() {
# Read from stdin and do something.
# E.g. just append to a file:
cat >> /tmp/some_file.txt
}

for delay in 120 30 30 3000 3000; do
delayed_ajax http://www.example.com/api/something my_handler $delay &
done

Linux shell script asynchronous commands and notification when completed

launch step 4 and 5 in background in your script (ending &), then simply call wait bash builtin before running step 6

Asynchronous bash script

I think that the safest way of doing this is to save the process ID of the child process and then periodically check to see if this is still running:

#!/bin/bash

mycommand &
child_pid=$!

while kill -0 $child_pid >/dev/null 2>&1; do
echo "Child process is still running"
sleep 1
done

echo "Child process has finished"

The variable $! will hold the process ID of the last process started in the background.

The kill -0 will not send a signal to the process, it only make kill return with a zero exit status if the given process ID exists and belongs to the user executing kill.

One could come up with a solution using pgrep too, but that will probably be a bit more "unsafe" in the sense that care must be taken not to catch any similar running processes.

How to run multiple commands at once asynchronously in fish shell?

When you place commands in parenthesis in Bash (or any POSIX shell), you are running them in a subshell, with the & of course placing the subshell in the background.

Fish doesn't have the exact concept of a subshell, but for your particular example, you can accomplish the same goal by running in a sub-process rather than a subshell.

fish -c "npm install -g npm@latest && npm install -g neovim bash-language-server vscode-langservers-extracted graphql -language-service-cli solidity-language-server typescript-language-server" &

There are several differences (and maybe others) between a subshell and a sub-process like this, but they don't matter for this particular scenario.



Related Topics



Leave a reply



Submit