0

I have been trying to write a script that will ask the user whether he/she should run the command again.

If the answer is yes, then it should execute the last command again. Even after 2nd time execution, it should ask the user whether should it run the last command or not. I want this to be happen until the answer becomes no, if the answer is no then it should exit.

i.e.

$ cat shellscript.sh
  echo foo
  printf 'Can I run the last command (y/n)?' 

If my answer is yes, then it should run the command "echo foo"

  # after the 1st time execution
  printf 'Can I run the last command again (y/n)?'

It will run the command again if the answer is yes, it will do the same (asking y/n and the execution) until the answer is yes. if no, then it should exit.

I think I need to implement some sort of loop, but I got confused as this is conditional script.

1

Using bash:

while [[ "$REPLY" != "no" ]]
do
  echo foo
  read -p "Can I run the last command (yes/no)?"
done

This requires a literal "no" answer to exit the loop, and as such I spelled out the "yes/no" prompt a bit more.

bash's read allows a custom prompt (the -p and string following), and stores the user's response in the $REPLY variable, which I assume is not "no" before entering the loop (it's empty if you haven't read anything yet).

  • Thanks a lot, It works perfect, I missed implementing while, it did the trick. thanks a lot again :). – smc Apr 12 '18 at 13:08
0

An alternative to Jeff's answer:

while true; do
    somecommand

    while true; do
        read -p 'Can I run the last command again (yes/no)? '

        case "$REPLY" in
            [Yy]*) break   ;;
            [Nn]*) break 2 ;;
            *) echo 'Sorry, what?' >&2
        esac
    done
done

The main difference here is that we're insisting on getting a valid reply from the user. A valid reply is any string that starts with either y or n (case ignored).

The break will break out of the answer-reading loop, while break 2 will additionally break out of the command loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.