1

background

bash 4.2

I have two files envar and main.sh

envar

...

# displays a spinner so that user knows the job is under processing.
spinner()
{ 
  spin='-\|/'
  i=0
  while kill -0 $1 2>/dev/null
  do
    i=$(( (i+1) %4 ))
    printf "\e[1;33m"
    printf "\r${spin:$i:1}"
    printf "\e[m"
    sleep .1
  done
}
...

main.sh

source envar

very_slow_and_dangerous_function &
pid=$!
spinner $pid
echo "$jobs done"

The problem

When someone press ctrl-c during spinner $pid the background shell becomes motherless.
I want both shells killed when ctrl-c or any other force signals happen.

How do I use Trap here?

2
  • 1
    How do you run these scripts? You mention bash but don't show a shebang or mention if you launch with bash main.sh or sh main.sh or something else. source is not portable, it's a bashishm for the standard . command. I doubt it will be relevant, but you never know.
    – terdon
    Jul 27, 2021 at 10:18
  • @terdon I use shebang #!/bin/bash. Thank you for the insight I didn't know source was bash only.
    – Lunartist
    Jul 28, 2021 at 0:43

1 Answer 1

1

You can try trapping SIGINT to kill 0 in envar:

$ cat envar
trap "kill 0" SIGINT
spinner()
{ 
  spin='-\|/'
  i=0
  while kill -0 $1 2>/dev/null
  do
    i=$(( (i+1) %4 ))
    printf "\e[1;33m"
    printf "\r${spin:$i:1}"
    printf "\e[m"
    sleep .1
  done
}

This will make the subshell also die. I tested with:

$ cat foo.sh
#!/bin/bash

## source your function file
. envar

sleep 600 &
pid=$!
spinner $pid
echo "$jobs done"

Running this and killing with Ctrl+C results in:

$ foo.sh
/^CTerminated
$ pgrep -c sleep
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .