skip to Main Content

I have the following script:

echo "User already exists, delete user? [Y/n] "
read -r -n 1 yn
echo "$yn was pressed"

When I run the script:

  • Pressing y or Y (without [Enter]) displays the keystroke on the screen.
  • Pressing [Enter] moves the cursor to a new line, but the following echo command doesn’t execute
  • Pressing [Enter] a second time causes the echo command to execute but doesn’t show the character I pressed

I expect it to not require me to press [Enter] twice.

I tried this as a variation:

echo "User already exists, delete user? [Y/n] "
read
echo "$REPLY was pressed"

And I still have to press the [Enter] key twice.

I also tried this:

read -r -n 1 -p "Y/y" response
case "$response" in
    [yY][eE][sS]|[yY]) 
        do_something
        ;;
    *)
        do_something_else
        ;;
esac

The result is similar. I never get shown a prompt and have to press [Enter] before [y] followed by [Enter] again to have any effect.

I have tried different variations including putting the prompt in the read command, but that was worse since the prompt never even showed up at that point.

What am I doing wrong? [apparently nothing – see update below]

UPDATE:

This script is running on a remote server over ssh as part of a bigger GitHub project. The server is a google cloud VM running Ubuntu 22.04 lts. my local machine is running Debian bookworm. I have both systems fully updated.

Upon testing the script by itself in its own test file test.sh, it works fine. Apparently there is something elsewhere in the project interfering with the read command which isn’t annotated in the project specifications and I can’t find where it could be overidden therein. I’ll have to talk with the project admins about it.

2

Answers


  1. Chosen as BEST ANSWER

    UPDATE:

    This script is running on a remote server over ssh as part of a bigger GitHub project. The server is a google cloud VM running Ubuntu 22.04 lts. my local machine is running Debian bookworm. I have both systems fully updated.

    Upon testing the script by itself in its own test file test.sh, it works fine. Apparently there is something elsewhere in the project interfering with the read command which isn't annotated in the project specifications and I can't find where it could be overidden therein. I'll have to talk with the project admins about it.


  2. The read command writes your output to a variable and you just need to process it.

    read -r -n 1 -p "Y/y" response
    case "$response" in
        [yY][eE][sS]|[yY]) 
            do_something
            ;;
        *)
            do_something_else
            ;;
    esac
    

    My version BASH

    bash --version
    GNU bash, версия 5.2.37(1)-release (x86_64-pc-linux-gnu)
    

    Answer: check your default shell. My script behaves differently in bash and zsh

    echo $SHELL
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search