Stewart Russell
Stewart Russell

Reputation: 337

Pause for loop until key is pressed

How can I run a for loop which pauses after each iteration until a key is pressed? for example, if I wanted to print the line number of file1, file2, file3, but only continuing each after pressing a key:

for f in dir/file? ; do wc -l $f ; pause until key is pressed ; done

Apologies if this is trivial, I'm new to the coding.

Upvotes: 15

Views: 10722

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133528

@Stewart: Try:

cat script.ksh
trap "echo exiting...; exit" SIGHUP SIGINT SIGTERM
for file in /tmp/*
do
        wc -l $file
echo "Waiting for key hit.."
read var
        if [[ -n $var ]]
        then
                continue
        fi
done

This script will be keep on running until/unless system get a signal to kill it (eg--> cntl+c etc). Let me know if this helps. Logic is simple created a trap first line of script to handle user's interruptions, then created a for loop which will look into a directory with all the files(you could change it accordingly to your need too). then wc -l of the current file as per yours post shown. Then ask user to enter a choice if user enters anything then it will go to loop again and again.

Upvotes: 1

Inian
Inian

Reputation: 85600

Use the read command to wait for a single character(-n1) input from the user

read -p "Press key to continue.. " -n1 -s

The options used from the man read page,

-n nchars return after reading NCHARS characters rather than waiting 
          for a newline, but honor a delimiter if fewer than NCHARS
          characters are read before the delimiter

-s      do not echo input coming from a terminal

-p      prompt output the string PROMPT without a trailing newline before
        attempting to read

Upvotes: 17

Related Questions