0

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.
1
  • 1
    To the extent that you claim to have "tried" kill -0 and found that it doesn't work, we need enough details to reproduce the failure mode ourselves. It is the correct solution; so to diagnose why it doesn't work for you we need to know exactly how you're trying to use it and exactly how it fails. Commented Sep 14, 2022 at 22:23

2 Answers 2

2
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.

Sign up to request clarification or add additional context in comments.

Comments

1
  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 ) & 

Comments