2

I am trying to make a script that runs 2 commands in a for loop as can be seen below:

#!/bin/bash for ((i=0; i<2; i++)); do sudo ./bin/llc test-rx -c 184 sleep 5 trap ctrl_c INT function ctrl_c() { echo "Trap: CTRL+C received, exit" exit } sudo ./bin/llc rxphylast done 

The 1st command (test-rx) continues to run as its is executed and it is stopped by pressing Ctrl+C. I want to stop this command in bash script so I used trap function as can be seen in the code. But when I execute the script, 1st command is running until I press Ctrl+C and then 2nd command (rxphylast) executes. So, in my case trap function is not working. Any advice on how to stop the 1st command in the script?

1 Answer 1

1
  1. Define the function and set the trap outside of the loop
  2. Define the function before you use it.

Try:

#!/bin/bash function ctrl_c() ( { echo "Trap: CTRL+C received, exit" exit } trap ctrl_c INT for ((i=0; i<2; i++)); do sudo ./bin/llc test-rx -c 184 sleep 5 sudo ./bin/llc rxphylast done 

Another example, not using ./bin/llc:

#!/bin/bash function ctrl_c() { echo "Trap: CTRL+C received, exit" exit } trap ctrl_c INT for ((i=0; i<2; i++)); do echo first program sudo find / -type f > /dev/null sleep 5 echo second program sudo find / -type f > /dev/null done 

Press Ctrl-C while the first find is running and it will print the "Trap: CTRL+C received, exit" message and exit immediately. Press Ctrl-C while the second find is running and it will do the same. This works the same whether sudo is used with the find commands or not - I only put that in there to make sure it wasn't sudo trapping and eating the Ctrl-C.

This is what happens when you run it and press Ctrl-C while the first find is running:

$ ./trap.sh first program ^CTrap: CTRL+C received, exit $ 
7
  • Well, it didn't work. Its the same I have to stop by using Ctrl+C Commented Apr 8, 2021 at 11:29
  • does ./bin/llc also trap SIGINT? The script works exactly as expected if i use other programs (like find / > /dev/null, I tested this with and without sudo) instead of llc. Commented Apr 8, 2021 at 12:05
  • I had to use ./bin/llc otherwise the commands test-rx and rxphylast will not work. Could u send me ur code with other programs? Commented Apr 8, 2021 at 12:12
  • Hi Cas, I tried the new program code that u wrote. Its working fine. ./bin is the location where llc shared library is present and using this llc i can use various commands like test-rx, rxphylast etc. May be its the issue of path ./bin/llc Commented Apr 8, 2021 at 12:35
  • It's not (and can't be) the path ./bin. It might be the program llc. All evidence so far points to that. Commented Apr 8, 2021 at 12:51

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.