Bash Question: HowTo Exit Script with User Input While Process is Running Mid-Loop?


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Bash Question: HowTo Exit Script with User Input While Process is Running Mid-Loop?
# 1  
Old 03-04-2014
Bash Question: HowTo Exit Script with User Input While Process is Running Mid-Loop?

Hi, I have written a script that allows me to repetitively play a music file $N times, which is specified through user input. However, if I want to exit the script before it has finished looping $N times, if I use CTRL+c, I have to CTRL+c however many times are left in order to complete the loop. For instance, if I specified that the song is to repeat 5 times, if during the first iteration through the loop, if I use CTRL+c to exit the script, I will have to press CTRL+c four more times before the script will terminate.

My objective is to be able to type 'q' or some character in order to quit the process. I have found limited information about this topic online, and what I have found has not worked for me.

Although my script provides more options than what is listed below, here it is in its most basic form (note - I'm using mplayer to play the audio file):

Code:
#!/bin/bash

echo -n "Enter the name of the song that you would like to play: "
read fileName
echo ""

echo -n "How many times would you like to repeat the song? "
read num
echo ""

for ((i=1; i<= $num; i++))
    do mplayer $fileName
done

Does anyone have any recommendations on how I can exit from the script using keyboard input in such a way that I'm not stuck in the loop and that the script actually terminates?

Thank you!
# 2  
Old 03-05-2014
I think trap might help you. You can customize how to respond to hardware signals such as Cntrl-c.
Man Page for trap (linux Section 1) - The UNIX and Linux Forums

Last edited by chacko193; 03-05-2014 at 12:54 AM.. Reason: typo...
# 3  
Old 03-05-2014
Bash Question: HowTo Exit Script with User Input While Process is Running Mid-Loop?

Thank you chacko193. I read the "trap" manpage and thought that it might work, but perhaps I'm not using it correctly... although it allows CTRL+c to exit the script, it also only allows the audio file to be executed one time; for some reason it won't loop for the specified number of times. Using the same code as in my previous example, I've added the trap signal:

Code:
for ((i=1; i<= $num; i++))
    do trap 'mplayer $fileName' 0
done

It seems like there should be a way to code this programatically rather than relying on another application like trap, but I just don't see it. I tried using the solutions that were suggested at the link below but only ended up with an infinite loop. (BTW - I keep trying to wrap this link in URL tags but for some reason vBulletin keeps telling me that I have reached the limit of having 5 URL's in my post so I'm instead wrapping it in CODE tags.)

Code:
https://www.unix.com/shell-programming-scripting/84624-nonblocking-i-o-bash-scripts.html

I'm not sure where to go from here.
# 4  
Old 03-05-2014
I'm not familiar with the bash shell but that line
Code:
do trap 'mplayer $fileName' 0

just doesn't look right. That is telling the shell to only execute "mplayer" when an interrupt 0 is captured.

The trap should be used to tell the script what to do when it receives certain signals, ie. how to clean up after itself.
Code:
trap 'exit 1' 1 2 3 15
for ((i=1; i<= $num; i++))
    mplayer $fileName
done

How can I trap interrupts in my shell script? - IS&T Contributions - Hermes

Last edited by port43; 03-05-2014 at 01:16 PM.. Reason: Added MIT link
# 5  
Old 03-05-2014
Thanks port43! Although this method does not accomplish what I had hoped to do in terms of "listening" for user input (pressing 'q' for quit), exiting the script with CTRL+c instead will work just fine for me and I'll be perfectly happy with that. The script is working very well now thanks to your input and suggestions. Before today, I had never heard of "trap".

As a musician, I will often times use this script when trying to commit a song or a series of songs to memory. Here's the new version:

Code:
echo -n "Would you like to repeat one file (1) or many files (M)?"
read quantity
echo ""
echo ""

echo -n "Enter the number of times you would like to play the file(s):"
read num
echo ""
echo ""

if [ $quantity == "1" ]
then
  echo -n "What is the name of the file?"
  read file
  trap 'exit 1' 1 2 3 15
  for ((i=1; i <= $num; i++))
     do mplayer $file
done

elif [ $quantity == "M" ]
then
  echo -n "Enter the file type or extension (mp3 / ogg / *)"
  read ext
  trap 'exit 1' 1 2 3 15
  for ((j=1; j <= $num; j++))
     do mplayer *.$ext
done

else
  echo ""
  echo -n "Invalid entry. Please try again."
  echo ""
fi

Thanks again!
# 6  
Old 03-05-2014
You don't need to repeat the trap command if they're identical; just add one at the top of the script. Don't forget to reset it once it's no more needed.
# 7  
Old 03-05-2014
Yep, as RudiC says, move the trap to the top of your script - one trap for the whole script (unless you want to change the way the script behaves at different times with different signals).
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Terminal running bash/rsync script does not close with exit (MacOS High SIerra)

Hello, I am running a bash script to do an rsync back on a computer running MacOS High Sierra. This is the script I am using, #!/bin/bash # main backup location, trailing slash included backup_loc="/Volumes/Archive_Volume/00_macos_backup/" # generic backup function function backup {... (12 Replies)
Discussion started by: LMHmedchem
12 Replies

2. Shell Programming and Scripting

Help Me. The script should not exit until the user gives an input.

Hi everyone, I'm new here and just a beginner in linux scripting. Just want to ask for help on this one. I am trying to create a script that will accept user input (year-month and user/s). I wanted to have the script to continue running, until the user inputs a DATE and name/s of user/s. ... (2 Replies)
Discussion started by: Helskadi
2 Replies

3. Shell Programming and Scripting

While loop with input in a bash script

I have the following while loop that I put in a script, demo.sh: while read rna; do aawork=$(echo "${rna}" | sed -n -e 's/\(...\)\1 /gp' | sed -f rna.sed) echo "$aawork" | sed 's/ //g' echo "$aawork" | tr ' ' '\012' | sort | sed '/^$/d' | uniq -c | sed 's/*\(*\) \(.*\)/\2: \... (3 Replies)
Discussion started by: faizlo
3 Replies

4. Shell Programming and Scripting

[BASH] Script to manage background scripts (running, finished, exit code)

Heyas, Since this question (similar) occur every now and then, and given the fact i was thinking about it just recently (1-2 weeks) anyway, i started to write something :p The last point for motivation was... (17 Replies)
Discussion started by: sea
17 Replies

5. Shell Programming and Scripting

Killing a bash process and running the second part of script

I want to run a script that calls remote ssh and if it gets hung, I want to be able to kill that part of the script and run another command in the script for example I have a statement like this: if ]; then export tapes=$(for tape in $(su - nacct -c 'ssh remote1 "cat... (1 Reply)
Discussion started by: newbie2010
1 Replies

6. Ubuntu

Exit user in bash script

I'm writing a bunch of scripts to automatically configure Ubuntu and I want to run the code below to remove the white dots from the login screen: sudo xhost +SI:localuser:lightdm sudo su lightdm -s /bin/bash gsettings set com.canonical.unity-greeter draw-grid false The problem is that... (3 Replies)
Discussion started by: maerlyngb
3 Replies

7. UNIX for Dummies Questions & Answers

Feed Input to a script running on bash

Hi Sir, I am just learning bash scripting and I came across a challenge. I need to input F11 to a script among many text inputs. For all the text inputs i did following. # sh test.sh < input.txt where input.txt contains all the text inputs in new lines. This worked fine until i... (1 Reply)
Discussion started by: gaurav kumar
1 Replies

8. Shell Programming and Scripting

Process running time by taking user input

Need help in scripting . Below is the situation and need your inputs Checking all the processes, scripts running time based on user input time . Below Example ps -aef -o user,pid,etime,stime,args| grep sleep <user> 28995 01:24 14:14:39 sleep 120 <user> 29385 00:52 14:15:10... (8 Replies)
Discussion started by: ajayram_arya
8 Replies

9. UNIX for Dummies Questions & Answers

Writing a loop to process multiple input files by a shell script

I have multiple input files that I want to manipulate using a shell script. The files are called 250.1 through 250.1000 but I only want the script to manipulate 250.300 through 250.1000. Before I was using the following script to manipulate the text files: for i in 250.*; do || awk... (4 Replies)
Discussion started by: evelibertine
4 Replies

10. Shell Programming and Scripting

exit script if user input not four characters

#!/usr/bin/bash ###script to input four characters. wxyz echo "input first string" read instring1 echo "input second string" read instring2 ## echo "first string is:" $instring1 echo "second string is:" $instring2 ##IF instring1 or instring2 are NOT 4 characters (xxxx) , exit 1. ##how?? ... (2 Replies)
Discussion started by: ajp7701
2 Replies
Login or Register to Ask a Question