Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to manipulate the loop by stdin

Status
Not open for further replies.

huangwason

Programmer
Oct 10, 2006
21
DE
I am going to write a loop, e.g
for (i=1; i<=10; i++)
do
echo "do test $i"
read
done

I would like to manipulate the loop manually. For instance, assume i=4 now, in the interval, when I press +, then perform next test 5, if I press -, then perform the previous test 3.
How to fulfill it? Thanks
 
Basically, any loop is ok as long as I could manipulate it. Here I only take an example.
 
Hi

Then I would start with something like this :
Code:
i=0
[b]while[/b] :; [b]do[/b]
  [b]echo[/b] [i]"do test $i ? ( + next / - prev / x exit )"[/i]
  [b]read[/b] c
  [b]case[/b] [i]"$c"[/i] [b]in[/b]
    [i]'+'[/i]) (( i++ )) ;;
    [i]'-'[/i]) (( i-- )) ;;
    [i]'x'[/i]) break ;;
  [b]esac[/b]
[b]done[/b]
What shell are you using ?

Feherke.
 
Hi

Good. [tt]bash[/tt]'s [tt]read[/tt] support the -n option :
help read said:
If -n is supplied with a non-zero NCHARS argument, read returns after NCHARS characters have been read.
This way you can achieve a [tt]getch[/tt]/[tt]readkey[/tt]/[tt]inkey[/tt] behavior :
Code:
i=0
[b]while[/b] :; [b]do[/b]
  [b]read[/b] -p [i]"do test $i ? ( + next / - prev / x exit )"[/i] -n 1 c
  [[ [i]"$c"[/i] ]] && [b]echo[/b]
  [b]case[/b] [i]"$c"[/i] [b]in[/b]
    [i]'+'[/i]) (( i++ )) ;;
    [i]'-'[/i]) (( i-- )) ;;
    [i]'x'[/i]) [b]break[/b] ;;
  [b]esac[/b]
[b]done[/b]

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top