bash - Loop until user presses 'C' in sh file
2014-07
What I want is as follows:
At first when user runs .sh file it displays following:
Review id:
You id is:XXX000YYY
Do you want to change it?[Press Y to change, C to continue]:
Now If user presses Y
then let him change id and again show this again, and do this until user presses C
to continue. How can I do this in shell script?
I tried following but don't know what to write in if conditions???
while :
do
echo "Enter id:"
read line
echo "Your id: $line"
echo "Do you want to change(Y to change, C to conntinue)?"
read ans
if [ $ans = C ] || [ $ans = c ]; then
/// .... finish the loop
elif [ $ans = y ] || [ $ans = Y ]; then
/// .... continue while loop
else
echo "Wrong selection."
/// .... continue while loop
fi
exit 0
I changed it to following, but now it's in infinite loop:
echo "Enter id:"
read line
echo "Your id: $line"
echo "Do you want to change(Y to change, C to conntinue)?"
read ans
while [ $ans = y ] || [ $ans = Y ];:
do
echo "Enter id:"
read line
echo "Your id: $line"
echo "Do you want to change(Y to change, C to conntinue)?"
read ans
done
The problem lies in this line:
while [ $ans = y ] || [ $ans = Y ];:
which should be
while [ $ans = y ] || [ $ans = Y ];
The issue is that the colon is a bash built-in that gets interpereted as true
. More information at What Is the Purpose of the `:' (colon) GNU Bash Builtin?.
The following code works for me
#!/bin/env bash
echo "Enter id:"
read line
echo "Your id: $line"
echo "Do you want to change(Y to change, C to conntinue)?"
read ans
while [ $ans == y ] || [ $ans == Y ] ;
do
echo "ANS: ${ans}"
echo "Enter id:"
read line
echo "Your id: $line"
echo "Do you want to change(Y to change, C to conntinue)?"
read ans
done
Note: it's always better to include a shebang at the top of your scripts.
If I run a for loop on the command line in sh, and I press control-C, it usually cancels the current running process, so I need to hold ^C until the shell itself catches it and breaks the loop. Is there a way to break current process and the loop immediately?
Easiest way I know would be to suspend the foreground job (^z), then kill it using the job id (kill %JOB_ID)
Example:
[me@host]$ while [ : ]; do less /etc/motd; done # Ctrl-C can't kill this
After a Ctrl-z
[1]+ Stopped less /etc/motd
[me@host]$ kill %1
[me@host]$
The number within the brackets ( [1] ) at the beginning of the suspension message gives you the job id.
You can also list out ids of suspended jobs using the the "jobs" command.