Home > Back-end >  Do Things While a Bash Script is Running
Do Things While a Bash Script is Running

Time:09-15

I have a very simple bash script; call it test.sh for practical purposes:

#!/bin/bash

sleep 5s

echo "Program is done."

I have another script that must take statistics with the /usr/bin/time command, for which I have set the cf alias; call this script statistics.sh:

#!/bin/bash

# Make sure to add the aliases.
shopt -s expand_aliases
source ~/.bash_aliases

# Get the command name.
name=${1:2}
echo "Executing script: $1"
echo "Name of script: $name"

# Run the script and get the process id.
cf $1 &
procID=$!

# While the $1 script is running do.
while [ <The script with id $1 is running>  ]
do
   echo "Here"
   sleep 1s
done

wait

# Exit message.
echo "Done running the program."

I have failed to make the while loop (properly) work; i.e., print "Here" 5 (or 4?) times.

Running the Program

I run the program as:

./statistics.sh './test.sh'

Whenever I am running it without the while loop it works perfectly, without printing the desired strings...of course.

What I Have Tried

I am lost in the sea of literature and 'solutions', but I have tried to set the <The script with id $1 is running> as:

  • kill -0 $1 2> /dev/null (and variations of)
  • I have tried to use the trap command, but I don't think that I understand it properly and thus it's not working.

CodePudding user response:

while kill -0 "$procID" 2>/dev/null
do
    echo Here
    sleep 1
done

If the condition is a command, you don't put it inside []. [ is an alias for the test command, it's used for testing conditional expressions, not the status of other commands.

CodePudding user response:

  1. launch the program into the background
  2. launch the "here" loop into the background as well
  3. wait for the program to complete
  4. then kill the here loop
cf "$1" &
procID=$!

( while true; do echo "Here"; sleep 1s; done ) &
loopID=$!

wait "$procID"
kill "$loopID"

We can give it some more pizzazz:

(
    spinner=('/' '-' '\' '|')
    # or: spinner=(' ' '░' '▒' '▓' '█' '▓' '▒' '░')
    # or: spinner=(' ' '○' '◎' '●' '◎' '○')
    n=${#spinner[@]}
    i=0
    while true; do
        printf '\r%s ' "${spinner[(i  )%n]}"
        sleep 0.1s
    done
) &
  • Related