Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shell script: run a block of code in the background without defining a new function?

Is there a way to 'inline' a block of code the run in the background without defining the block as a function? I was thinking something like:

( do something; a bit more; finally this ) &
( more things; etc ...; ) &
wait
proceed ... 

I suppose it's only one line extra define a single-use function and then immediately use it but I was curious and didn't find anything searching.

like image 494
mathtick Avatar asked Dec 22 '10 17:12

mathtick


People also ask

How do I keep a shell script running in the background?

Use bg to Send Running Commands to the Background You can easily send such commands to the background by hitting the Ctrl + Z keys and then using the bg command. Hitting Ctrl + Z stops the running process, and bg takes it to the background. You can view a list of all background tasks by typing jobs in the terminal.

How do I run something in the background in bash?

To send a running command in the background: If users have already started a certain command and while they were using their system, their command-line blocks up, then they can suspend the execution of their currently foregrounded process by using “ctrl+z” for windows and “command+z” for mac systems.

Do bash functions need to be defined before use?

There are two ways to implement Bash functions: Inside a shell script, where the function definition must be before any calls on the function. Alongside other bash alias commands and directly in the terminal as a command.


2 Answers

#!/bin/sh
{
    echo "sleeping for 5 seconds"
    sleep 5
    echo "woke up"
} &
echo "waiting"
wait
echo "proceed"

Output

$ ./bgblock
waiting
sleeping for 5 seconds
woke up
proceed
like image 121
SiegeX Avatar answered Oct 27 '22 06:10

SiegeX


I could do it with something like this:

#!/bin/sh
{
    echo "sleeping for 5 seconds"
    sleep 5
    echo "woke up"
} 1>/dev/null 2>&1 &
like image 22
Pascal V. Avatar answered Oct 27 '22 05:10

Pascal V.