Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Do Things While a Bash Script is Running

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading