Linux yes no bash

Bash Script — Prompt to Confirm (Y/N, YES/NO)

How do I prompt a user for confirmation in bash script?

You can use the built-in read command ; Use the -p option to prompt the user with a question. Bash has select for this purpose.

How do I automatically answer Y in bash script?

Let’s run the yes command in a terminal: y y y . It will just produce the output y repeatedly. Therefore, our script will answer y if any prompt is generated by the command and won’t be blocked during its execution.

How do I prompt for input in bash?

  1. #!/bin/bash.
  2. # Read the user input.
  3. echo «Enter the user name: «
  4. read first_name.
  5. echo «The Current User Name is $first_name»
  6. echo.
  7. echo «Enter other users’names: «
  8. read name1 name2 name3.

How do you answer yes or no in Linux?

Simply type yes , a space, the string you wish to use, and then press Enter. This is often used to cause yes to generate an output stream of “yes” or “no” strings.

How do I read in bash?

Type two words and press “Enter”. read and echo are enclosed in parentheses and executed in the same subshell. By default, read interprets the backslash as an escape character, which sometimes may cause unexpected behavior. To disable backslash escaping, invoke the command with the -r option.

How do I see users in bash?

  1. echo «$USER»
  2. u=»$USER» echo «User name $u»
  3. id -u -n.
  4. id -u.
  5. #!/bin/bash _user=»$(id -u -n)» _uid=»$(id -u)» echo «User name : $_user» echo «User name ID (UID) : $_uid»

How do I pass a yes to a bash script?

To answer n to all questions, replace yes with yes n . For a predefined mix of y and n , you can replace yes with: printf ‘%s\n’ y n n y y n.

How do you answer yn in CMD?

Pipe the echo [y|n] to the commands in Windows PowerShell or CMD that ask “Yes/No” questions, to answer them automatically.

How do I expect a bash script?

  1. Step 1 : Create a new file. vi expectcmd.
  2. Step 2 : Copy and paste below given content in file. Change the value as per your information in variables – .
  3. Step 3: Make your file executable by owner of file , run the given below command. chmod 750 expectcmd.
  4. Step 4: Give commands as argument along with expectcmd script.

How do I read standard input in bash?

  1. Use cat , not less . It’s faster and you don’t need pagination.
  2. Use $1 to read from first argument file (if present) or $* to read from all files (if present). If these variables are empty, read from stdin (like cat does) #!/bin/bash cat $* | .
Читайте также:  Linux get all disks

What do you use to forward errors to a file?

  1. Redirect stdout to one file and stderr to another file: command > out 2>error.
  2. Redirect stdout to a file ( >out ), and then redirect stderr to stdout ( 2>&1 ): command >out 2>&1.

How do I run a shell script from command line arguments?

  1. $* – Store all command line arguments.
  2. $@ – Store all command line arguments.
  3. $# – Store count of command line arguments.
  4. $0 – Store name of script itself.
  5. $1 – Store first command line argument.
  6. $2 – Store second command line argument.
  7. $3 – Store third command line argument.

How To Install MySQL 8.0 on Ubuntu 20.04

Mysql

How To Install MySQL 8.0 on Ubuntu 20.04Step 1: Add MySQL APT repository in Ubuntu. Ubuntu already comes with the default MySQL package repositories. .

How to Install and Use FFmpeg on Ubuntu 20.04

Ffmpeg

How to Install and Use FFmpeg on Ubuntu 20.04Prerequisites. You must have shell access with sudo privileged account access on your Ubuntu 20.04 system.

How To Install OCS Inventory Server on CentOS 8

Install

How to Install OCS Inventory Asset Management Software CentOS 8Prerequisites.Getting Started.Install Apache, MariaDB, and PHP.Configure MariaDB Databa.

Latest news, practical advice, detailed reviews and guides. We have everything about the Linux operating system

Источник

How to prompt for yes or no in bash? [duplicate]

How do I ask a yes/no type question in Bash? I ask the question. echo «Do you like pie?» And receive the answer. read pie How do I do something if the answer is yes , or starts with y (so yes and yeah, etc, will work too).

For zsh users, the -q option is available. Read only one character from the terminal and set name to ‘y’ if this character was ‘y’ or ‘Y’ and to ‘n’ otherwise. With this flag set the return status is zero only if the character was ‘y’ or ‘Y’. Note that this always reads from the terminal, even if used with the -p or -u or -z flags or with redirected input. This option may also be used within zle widgets.

@UlysseBN zsh never ceases to amaze me! I don’t remember what this original question was for, but I’m going to keep that in mind for when I have control of the shell executing my script — thank you!

6 Answers 6

I like to use the following function:

So in your script you can use like this:

yes_or_no "$message" && do_something 

In case the user presses any key other than [yYnN] it will repeat the message.

read -p «$@ [y/n]: » is incorrect, you need to use $* or the read will explode if the function is called with more than one argument. Also, technically this should use yes_or_not «$@» but for this that only matters if you use yes_or_not ‘foo bar’ and then the user doesn’t input yes or no (the inner spaces will then get lost).

I added a question mark after the $* . This also works great with an if block: if yes_or_no «Do next task»; then ;;;; fi constructs

read -e -p "Do you like pie? " choice [[ "$choice" == [Yy]* ]] && echo "doing something" || echo "that was a no" 

Pattern starting with Y or y will be taken as yes .

Читайте также:  Astra linux фильтрация трафика

I like Jahid’s oneliner. Here is a slight simplification of it:

[[ "$(read -e -p 'Continue? [y/N]> '; echo $REPLY)" == [Yy]* ]] 
$ [[ "$(read -e -p 'Continue? [y/N]> '; echo $REPLY)" == [Yy]* ]] && echo Continuing || echo Stopping Continue? [y/N]> yes Continuing $ for test_string in y Y yes YES no ''; do echo "Test String: '$test_string'"; echo $test_string | [[ "$(read -e -p 'Continue? [y/N]>'; echo $REPLY)" == [Yy]* ]] && echo Continuing || echo Stopping; done Test String: 'y' Continuing Test String: 'Y' Continuing Test String: 'yes' Continuing Test String: 'YES' Continuing Test String: 'no' Stopping Test String: '' Stopping 

In response to a comment, I’m going to add an adaptation to make this work in zsh .

I would never write a shell script in zsh even though it is now my primary interactive shell. I still write all scripts in bash or sh . However, since you sometimes need to script modifications to your interactive shell (ex: source ~/dev/set_env ), you might want to include prompting.

#! /usr/bin/env zsh [[ "$(echo -n 'Continue? [y/N]> ' >&2; read; echo $REPLY)" == [Yy]* ]] \ && echo Continuing \ || echo Stopping 

Источник

Is there any default function/utility to prompt the user for yes/no in a Bash script?

Ah, there is something built-in: zenity is a graphical dialog program:

if zenity --question --text="Is this OK?" --ok-label=Yes --cancel-label=No then # user clicked "Yes" else # user clicked "No" fi 

In addition to zenity , you can use one of:

if dialog --yesno "Is this OK?" 0 0; then . if whiptail --yesno "Is this OK?" 0 0; then . 

That looks fine to me. I would just make it a bit less «do or die»:

That way you can do something like:

if check_yes_no "Do important stuff? [Y/n] "; then # do the important stuff else # do something else fi # continue with the rest of your script 

With @muru’s select suggestion, the function can be very terse:

check_yes_no () < echo "$1" local ans PS3=">" select ans in Yes No; do [[ $ans == Yes ]] && return 0 [[ $ans == No ]] && return 1 done > 

As a conclusion I wrote this script:

#!/bin/bash usage() < echo "Show yes/no dialog, returns 0 or 1 depending on user answer" echo "Usage: $0 [OPTIONS] -x force to use GUI dialog -m message that user will see" 1>&2 exit 1; > while getopts m:xh opts; do case $ in x) FORCE_GUI=true; ;; m) MSG=$ ;; h) usage ;; esac done if [ -z "$MSG" ];then usage fi # Yes/no dialog. # If the user enters n/N, return 1. while true; do if [ -z $FORCE_GUI ]; then read -p "$MSG" yn case "$yn" in [Yy] ) exit 0;; [Nn] ) echo "Aborting. " >&1 exit 1;; * ) echo "Please answer y or n for yes or no.";; esac else if [ -z $DISPLAY ]; then echo "DISPLAY variable is not set" >&1 ; exit 1; fi if zenity --question --text="$MSG" --ok-label=Yes --cancel-label=No; then exit 0 else echo "Aborting. " >&1 exit 1 fi fi done; 

Latest version of script can be found here. Fill free to change/edit

 read -p ". Are You sure [y/N]? " -n 1 if [[ ! $REPLY =~ ^[Yy]$ ]]; then echo ". Canceled by user." exit 1 fi 
 read -p ". Are You sure [Y/n]" -n 1 if [[ $REPLY =~ ^[Nn]$ ]]; then echo ". Canceled by user." exit 1 fi 
 read -p 'Are you sure you want to continue? (y/n) ' -n 1 confirmation echo '' if [[ $confirmation != 'y' && $confirmation != 'Y' ]]; then exit 3 fi # Code to execute if user wants to continue here. 

You must log in to answer this question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Читайте также:  Linux vps with gui

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.14.43533

Ubuntu and the circle of friends logo are trade marks of Canonical Limited and are used under licence.

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

How do I prompt a user for confirmation in bash script? [duplicate]

I want to put a quick «are you sure?» prompt for confirmation at the top of a potentially dangerous bash script, what’s the easiest/best way to do this?

10 Answers 10

read -p "Are you sure? " -n 1 -r echo # (optional) move to a new line if [[ $REPLY =~ ^[Yy]$ ]] then # do dangerous stuff fi 

I incorporated levislevis85‘s suggestion (thanks!) and added the -n option to read to accept one character without the need to press Enter . You can use one or both of these.

Also, the negated form might look like this:

read -p "Are you sure? " -n 1 -r echo # (optional) move to a new line if [[ ! $REPLY =~ ^[Yy]$ ]] then [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1 # handle exits from shell or function but don't exit interactive shell fi 

However, as pointed out by Erich, under some circumstances such as a syntax error caused by the script being run in the wrong shell, the negated form could allow the script to continue to the «dangerous stuff». The failure mode should favor the safest outcome so only the first, non-negated if should be used.

Explanation:

The read command outputs the prompt ( -p «prompt» ) then accepts one character ( -n 1 ) and accepts backslashes literally ( -r ) (otherwise read would see the backslash as an escape and wait for a second character). The default variable for read to store the result in is $REPLY if you don’t supply a name like this: read -p «my prompt» -n 1 -r my_var

The if statement uses a regular expression to check if the character in $REPLY matches ( =~ ) an upper or lower case «Y». The regular expression used here says «a string starting ( ^ ) and consisting solely of one of a list of characters in a bracket expression ( [Yy] ) and ending ( $ )». The anchors ( ^ and $ ) prevent matching longer strings. In this case they help reinforce the one-character limit set in the read command.

The negated form uses the logical «not» operator ( ! ) to match ( =~ ) any character that is not «Y» or «y». An alternative way to express this is less readable and doesn’t as clearly express the intent in my opinion in this instance. However, this is what it would look like: if [[ $REPLY =~ ^[^Yy]$ ]]

Источник

Оцените статью
Adblock
detector