Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell user prompt (Y/n)

Tags:

linux

bash

shell

I just wanted to write a small sript for copying some files for my NAS, so I'm not very experienced in Shell-Scripting. I know that many command line tools on Linux use the following sheme for Yes/No inputs

Are you yure [Y/n]

where the capitalized letter indicates the standard action which would also be started by hitting Enter. Which is nice for a quick usage.

I also want to implement something like this, but I have some trouble with caching the Enter key. Here is what I got so far:

read -p "Are you sure? [Y/n] " response

    case $response in [yY][eE][sS]|[yY]|[jJ]|[#insert ENTER codition here#]) 

        echo
        echo files will be moved
        echo
        ;;
    *)
        echo
        echo canceld
        echo
        ;;
esac

I can add what ever I want but it just won't work with Enter.

like image 984
globus243 Avatar asked Nov 30 '22 01:11

globus243


2 Answers

Here's a quick solution:

read -p "Are you sure? [Y/n] " response

case $response in [yY][eE][sS]|[yY]|[jJ]|'') 

    echo
    echo files will be moved
    echo
    ;;
    *)
    echo
    echo canceled
    echo
    ;;
esac
like image 197
Aaron Okano Avatar answered Dec 04 '22 06:12

Aaron Okano


If you are using bash 4, you can "pre-seed" the response with the default answer, so that you don't have to treat ENTER explicitly. (You can also standardize the case of response to simplify the case statement.

read -p "Are you sure? [Y/n] " -ei "y" response
response=${response,,}  # convert to lowercase
case $response in
    y|ye|yes)
      echo
      echo files will be moved
      echo
    ;;
    *)
      echo
      echo cancelled
      echo
      ;;
like image 34
chepner Avatar answered Dec 04 '22 04:12

chepner