However bash I punctual for Sure/Nary/Cancel enter successful a Linux ammunition book?

However bash I punctual for Sure/Nary/Cancel enter successful a Linux ammunition book?

I privation to intermission enter successful a ammunition book, and punctual the person for selections.
The modular Yes, No, oregon Cancel kind motion.
However bash I execute this successful a emblematic bash punctual?


A wide disposable methodology to acquire person enter astatine a ammunition punctual is the read bid. Present is a objection:

while true; do read -p "Do you wish to install this program? " yn case $yn in [Yy]* ) make install; break;; [Nn]* ) exit;; * ) echo "Please answer yes or no.";; esacdone

Different methodology, pointed retired by Steven Huwig, is Bash's select bid. Present is the aforesaid illustration utilizing select:

echo "Do you wish to install this program?"select yn in "Yes" "No"; do case $yn in Yes ) make install; break;; No ) exit;; esacdone

With select you don't demand to sanitize the enter – it shows the disposable selections, and you kind a figure corresponding to your prime. It besides loops robotically, truthful location's nary demand for a while true loop to retry if they springiness invalid enter. If you privation to let much versatile enter (accepting the phrases of the choices, instead than conscionable their figure), you tin change it similar this:

echo "Do you wish to install this program?"select strictreply in "Yes" "No"; do relaxedreply=${strictreply:-$REPLY} case $relaxedreply in Yes | yes | y ) make install; break;; No | no | n ) exit;; esacdone

Besides, Léa Gris demonstrated a manner to brand the petition communication agnostic successful her reply. Adapting my archetypal illustration to amended service aggregate languages mightiness expression similar this:

set -- $(locale LC_MESSAGES)yesexpr="$1"; noexpr="$2"; yesword="$3"; noword="$4"while true; do read -p "Install (${yesword} / ${noword})? " yn if [[ "$yn" =~ $yesexpr ]]; then make install; exit; fi if [[ "$yn" =~ $noexpr ]]; then exit; fi echo "Answer ${yesword} / ${noword}."done

Evidently another connection strings stay untranslated present (Instal, Reply) which would demand to beryllium addressed successful a much full accomplished translation, however equal a partial translation would beryllium adjuvant successful galore instances.


Eventually, delight cheque retired the fantabulous reply by F. Hauri.


Astatine slightest 5 solutions for 1 generic motion.

Relying connected

  • compliant: might activity connected mediocre techniques with generic environments
  • circumstantial: utilizing truthful known as bashisms

and if you privation

  • elemental 'successful formation'' motion / reply (generic options)
  • beautiful formatted interfaces, similar oregon much graphical utilizing libgtk oregon libqt...
  • usage almighty readline past capableness

1. POSIX generic options

You might usage the read bid, adopted by if ... then ... else:

#/bin/shprintf 'Is this a good question (y/n)? 'read answerif [ "$answer" != "${answer#[Yy]}" ] ;then echo Yeselse echo Nofi

(Acknowledgment to Adam Katz's remark: Changed the trial with the fresh 1 supra that's much moveable and avoids 1 fork :)

1.1 POSIX, however azygous cardinal characteristic

However if you don't privation the person to person to deed Instrument, you might compose:

(Edited: Arsenic @JonathanLeffler rightly propose, redeeming stty's configuration might beryllium amended than merely unit them to sane.)

#/bin/shprintf 'Is this a good question (y/n)? 'old_stty_cfg=$(stty -g)stty raw -echo ; answer=$(head -c 1) ; stty $old_stty_cfg # Careful playing with sttyif [ "$answer" != "${answer#[Yy]}" ];then echo Yeselse echo Nofi

1.2 POSIX, however azygous cardinal characteristic localized

Utilizing locale bid, impressed by Léa Gris's thought for dealing with locales, however for this I conscionable demand *yes expression*:

#/bin/shyExpr=$(locale yesexpr) printf 'Is this a good question (y/n)? 'old_stty_cfg=$(stty -g)stty raw -echo ; answer=$(head -c 1) ; stty $old_stty_cfg # Careful playing with sttyif [ "$answer" != "${answer#${yExpr#^}}" ];then echo Yeselse echo Nofi

Line: This was examined nether , , , and !

1.Three Aforesaid, however ready explicitly for y, n oregon from locale

#/bin/shset -- $(locale LC_MESSAGES)yExpr="$1"; nExpr="$2"printf 'Is this a good question (y/n)? 'old_stty_cfg=$(stty -g)stty raw -echoanswer=$( while ! head -c 1 | grep "$yExpr\|$nExpr" ;do true ;done )stty $old_stty_cfgif [ "$answer" != "${answer#${yExpr#^}}" ];then echo Yeselse echo Nofi

1.Four Inquire for Y/N POSIX ammunition relation with azygous cardinal characteristic

If you program to usage this repetitively, you whitethorn privation to make a devoted relation:

#/bin/shaskFor() { __aF_yExpr="$(locale yesexpr)" __aF_nExpr="$(locale noexpr)" printf '%s? ' "$*" __aF_oStty=$(stty -g) stty raw -echo __aF_key=$( while ! head -c 1| grep "$__aF_yExpr\|$__aF_nExpr"; do :;done ) stty $__aF_oStty if [ "$__aF_key" != "${__aF_key#${__aF_yExpr#^}}" ]; then echo Yes else echo No; return 1 fi}
verbEcho() { [ "$quietMode" -gt 0 ] || echo $*;}askFor Enable verbose modequietMode=$?verbEcho Ask for continuingaskFor Do you want to continue this demonstration || exittoInstall=''for package in moon-buggy pacman4console junior-games-text; do verbEcho Ask for Installation of $package if askFor Do I install full "$package"; then verbEcho "Add $package to list" toInstall="$toInstall $package" fidoneif [ -z "$toInstall" ]; then echo Nothing to do.elif askFor Do you really want to install $toInstall; then verbEcho Proceed installation of $toInstall echo sudo apt install $toInstall # Drop `echo` for real installationfi

1.4b Aforesaid, bu strictly reply Truthful motion: Inquire for Sure / Nary / Cancel

Aforesaid relation, however if you deed flight cardinal Esc, this volition instantly discontinue the book (Line: exit might beryllium changed by return 2, to beryllium checked by chief book).

#/bin/shaskFor() { __aF_yExpr="$(locale yesexpr)" __aF_nExpr="$(locale noexpr)" printf '%s? ' "$*" __aF_oStty=$(stty -g) stty raw -echo __aF_key=$( while ! head -c 1| grep -P "\e|$__aF_yExpr|$__aF_nExpr"; do :;done ) stty $__aF_oStty if [ "$__aF_key" != "${__aF_key#${__aF_yExpr#^}}" ]; then echo Yes return 0 elif [ "$__aF_key" != "${__aF_key#${__aF_nExpr#^}}" ]; then echo No return 1 fi echo Cancel exit}

You might usage aforesaid example book for investigating this interpretation.

2. Utilizing devoted instruments

Location are galore instruments which had been constructed utilizing libncurses, libgtk, libqt oregon another graphical libraries. For illustration, utilizing whiptail:

if whiptail --yesno "Is this a good question" 20 60 ;then echo Yeselse echo Nofi

Relying connected your scheme, you whitethorn demand to regenerate whiptail with different similiar implement:

dialog --yesno "Is this a good question" 20 60 && echo Yesgdialog --yesno "Is this a good question" 20 60 && echo Yeskdialog --yesno "Is this a good question" 20 60 && echo Yes

wherever 20 is tallness of dialog container successful figure of traces and 60 is width of the dialog container. These instruments each person close aforesaid syntax.

DIALOG=whiptailif [ -x /usr/bin/gdialog ] ;then DIALOG=gdialog ; fiif [ -x /usr/bin/xdialog ] ;then DIALOG=xdialog ; fi...$DIALOG --yesno ...

Three. Bash circumstantial options

Basal successful formation methodology

read -p "Is this a good question (y/n)? " answercase ${answer:0:1} in y|Y ) echo Yes ;; * ) echo No ;;esac

I like to usage case truthful I might equal trial for yes | ja | si | oui if wanted...

successful formation with azygous cardinal characteristic

Nether bash, we tin specify the dimension of meant enter for for the read bid:

read -n 1 -p "Is this a good question (y/n)? " answer

Nether bash, read bid accepts a timeout parameter, which might beryllium utile.

read -t 3 -n 1 -p "Is this a good question (Y/n)? " answer[ -z "$answer" ] && answer="Yes" # if 'yes' have to be default choice

Timeout with countdown:

i=6 ;while ((i-->1)) &&! read -sn 1 -t 1 -p $'\rIs this a good question (Y/n)? '$i$'..\e[3D' answer;do :;done ;[[ $answer == [nN] ]] && answer=No || answer=Yes ;echo "$answer "

Three. Any tips for devoted instruments

Much blase dialog bins, past elemental yes - no functions:

dialog --menu "Is this a good question" 20 60 12 y Yes n No m Maybe

Advancement barroom:

dialog --gauge "Filling the tank" 20 60 0 < <( for i in {1..100};do printf "XXX\n%d\n%(%a %b %T)T progress: %d\nXXX\n" $i -1 $i sleep .033 done) 

Small demo:

#!/bin/shwhile true ;do [ -x "$(which ${DIALOG%% *})" ] || DIALOG=dialog DIALOG=$($DIALOG --menu "Which tool for next run?" 20 60 12 2>&1 \ whiptail "dialog boxes from shell scripts" >/dev/tty \ dialog "dialog boxes from shell with ncurses" \ gdialog "dialog boxes from shell with Gtk" \ kdialog "dialog boxes from shell with Kde" ) || break clear;echo "Choosed: $DIALOG." for i in `seq 1 100`;do date +"`printf "XXX\n%d\n%%a %%b %%T progress: %d\nXXX\n" $i $i`" sleep .0125 done | $DIALOG --gauge "Filling the tank" 20 60 0 $DIALOG --infobox "This is a simple info box\n\nNo action required" 20 60 sleep 3 if $DIALOG --yesno "Do you like this demo?" 20 60 ;then AnsYesNo=Yes; else AnsYesNo=No; fi AnsInput=$($DIALOG --inputbox "A text:" 20 60 "Text here..." 2>&1 >/dev/tty) AnsPass=$($DIALOG --passwordbox "A secret:" 20 60 "First..." 2>&1 >/dev/tty) $DIALOG --textbox /etc/motd 20 60 AnsCkLst=$($DIALOG --checklist "Check some..." 20 60 12 \ Correct "This demo is useful" off \ Fun "This demo is nice" off \ Strong "This demo is complex" on 2>&1 >/dev/tty) AnsRadio=$($DIALOG --radiolist "I will:" 20 60 12 \ " -1" "Downgrade this answer" off \ " 0" "Not do anything" on \ " +1" "Upgrade this anser" off 2>&1 >/dev/tty) out="Your answers:\nLike: $AnsYesNo\nInput: $AnsInput\nSecret: $AnsPass" $DIALOG --msgbox "$out\nAttribs: $AnsCkLst\nNote: $AnsRadio" 20 60 done

Much samples? Person a expression astatine Utilizing whiptail for selecting USB instrumentality and USB detachable retention selector: USBKeyChooser

5. Utilizing readline's past

Illustration:

#!/bin/bashset -iHISTFILE=~/.myscript.historyhistory -chistory -rmyread() { read -e -p '> ' $1 history -s ${!1}}trap 'history -a;exit' 0 1 2 3 6while myread line;do case ${line%% *} in exit ) break ;; * ) echo "Doing something with '$line'" ;; esac done

This volition make a record .myscript.history successful your $HOME listing, than you might usage readline's past instructions, similar Ahead, Behind, Ctrl+r and others.

6. Utilizing fresh fzf inferior

Location are a fresh inferior known as fzf for fuzzy finder.

if [[ $(fzf --header='Delete current directory?' --tac <<<$'Yes\nNo' ) == Yes ]]; then echo rm .fi

oregon

if [[ $(fzf --header='Delete current directory?' --tac < <(locale yesstr nostr )) == $(locale yesstr) ]]; then echo rm .fi

This implement is precise versatile and powerfull, utilizing preview framework and cardinal binging.

Present is a example, utilizing catimg, pdftotext, batcat, ghostscript and w3m outer instruments, for populating preview framework, past volition populate a bash array for storing person action:

#!/bin/bashfPrev() { printf "\e[40m%s\e[0m\n" "$(var="$1"; cd "${var%/*}"; ls -dhl "${var##*/}")"; case $(file -b --mime-type "$1") in text/html) w3m -T text/html -dump "$1" ;; text/x-*) batcat --color always "$1" ;; text*) cat "$1" ;; application/postscript) gs -sDEVICE=png16m -r60 -sOutputFile=- -q \ -dNOPAUSE -dBATCH -dSAFER - -c quit < "$1" 2> /dev/null | catimg -w $((2*COLUMNS)) - ;; image/svg+xml) inkscape -d 100 --export-type=png -o - "$1" | catimg -w $((2*COLUMNS)) - ;; image*) catimg -w $((2*COLUMNS)) "$1" ;; application/pdf) pdftotext -layout - - < "$1" ;; inode/directory) /bin/ls --color=alway -bhlt "$1" | sed "s/\( \+[^ ]\+\)\{3\}//" ;; *) cat -e "$1" ;; esac}export -f fPrev;mapfile -td '' array < <( fzf -m -e -i --print0 --preview='fPrev {}' --preview-window='right,70%' < <( find "$@" -maxdepth 2 -exec ls -1dtr {} + ))declare -p array

I posted present, different fzf / bash illustration, connecting to a database (sqlite3 for the example), past usage SQL requests for populating preview framework. (Saved arsenic a tarball compressed by zstandard, might beryllium unfastened by contemporary GNU tar, by tar -xf fzfDbDemo.tzst oregon by zstdcat fzfDbDemo.tzst | tar -x for aged variations of tar.)


Successful Linux ammunition scripting, guaranteeing the palmy oregon unsuccessful execution of instructions is important for creating sturdy and dependable scripts. Frequently, you demand to confirm if a bid accomplished arsenic anticipated earlier continuing with consequent steps. This includes checking the exit position of the former bid, which is a numeric worth indicating occurrence (normally Zero) oregon nonaccomplishment (immoderate another worth). By incorporating conditional statements primarily based connected these exit statuses, you tin power the travel of your book, grip errors gracefully, and brand your scripts much resilient to sudden points. This article volition usher you done assorted strategies to cheque the exit position successful Bash, enabling you to compose much effectual and mistake-resistant scripts.

However to Find Bid Occurrence oregon Nonaccomplishment successful Bash Scripts

Knowing however to find if a bid succeeded oregon failed successful a Bash book is cardinal for effectual scripting. The exit position, besides recognized arsenic the instrument codification, offers this accusation. By normal, an exit position of Zero signifies occurrence, piece immoderate non-zero worth signifies nonaccomplishment. This permits scripts to respond appropriately to the result of all bid. For case, you mightiness privation to continue with a record processing project lone if the record was efficiently copied, oregon you mightiness privation to log an mistake communication if a web transportation fails. Checking the exit position ensures your book executes arsenic meant, equal once sudden errors happen.

Utilizing $? to Entree the Exit Position

The $? adaptable successful Bash shops the exit position of the about late executed bid. This adaptable is your capital implement for checking whether or not a bid succeeded oregon failed. Straight last moving a bid, you tin entree $? to retrieve its exit position. Utilizing this worth successful conditional statements permits you to make scripts that react dynamically to antithetic outcomes. For illustration, you tin cheque if a record was efficiently created and past continue to compose information into it, oregon you tin grip the lawsuit wherever the record instauration fails by logging an mistake oregon retrying the cognition. This makes your scripts much sturdy and dependable.

 Example: Checking if a directory was successfully created mkdir mydirectory if [ $? -eq 0 ]; then echo "Directory created successfully." else echo "Failed to create directory." fi 

Implementing Conditional Logic Primarily based connected Bid Result

1 of the about effectual methods to grip bid outcomes is by utilizing conditional logic successful your Bash scripts. Conditional statements, specified arsenic if, past, other, and elif, let you to execute antithetic blocks of codification primarily based connected the exit position of a bid. This allows your scripts to respond intelligently to assorted situations, dealing with errors and guaranteeing the accurate series of operations. By checking the exit position inside these conditional blocks, you tin make scripts that are some sturdy and adaptable, capable to grip sudden points gracefully and proceed execution with out crashing.

Array Naming Dilemma: Singular vs. Plural Names

Examples of Conditional Checks

Present are a fewer examples demonstrating however to usage conditional checks primarily based connected bid outcomes successful Bash scripting:

  • Checking if a record exists earlier making an attempt to publication it:
 if [ -f myfile.txt ]; then cat myfile.txt if [ $? -eq 0 ]; then echo "File read successfully." else echo "Failed to read file." fi else echo "File does not exist." fi 
  • Verifying palmy execution of a programme:
 myprogram if [ $? -eq 0 ]; then echo "Program executed successfully." else echo "Program failed to execute." fi 
  • Conditional bid execution utilizing && and ||:
 Execute command2 only if command1 succeeds command1 && command2 Execute command2 only if command1 fails command1 || command2 

Utilizing && and || tin brand your scripts much concise and readable. The && function ensures that the 2nd bid lone runs if the archetypal bid succeeds (returns an exit position of Zero). Conversely, the || function ensures that the 2nd bid lone runs if the archetypal bid fails (returns a non-zero exit position). These operators are peculiarly utile for chaining instructions wherever the occurrence of 1 bid is a prerequisite for the adjacent.

Array: Evaluating Strategies for Checking Exit Position

Technique Statement Illustration
$? Accesses the exit position of the past executed bid.
 command; echo $? 
if statements Executes antithetic blocks of codification primarily based connected the exit position.
 if [ $? -eq 0 ]; then ...; else ...; fi 
&& and || operators Chains instructions primarily based connected the occurrence oregon nonaccomplishment of the former bid.
 command1 && command2; command1 || command2 
"Effectual mistake dealing with is a cornerstone of sturdy ammunition scripting. By leveraging exit statuses and conditional logic, you tin make scripts that gracefully grip sudden points and guarantee dependable execution."

Successful abstract, checking the exit position of instructions successful Bash scripts is indispensable for penning dependable and sturdy codification. By utilizing the $? adaptable and implementing conditional logic, you tin power the travel of your book, grip errors efficaciously, and guarantee that your book behaves arsenic anticipated, equal once sudden issues originate. These methods are invaluable for immoderate ammunition scripting project, from elemental automation to analyzable scheme medication scripts. Pattern these strategies to go proficient successful mistake dealing with and better the general choice of your scripts. Larn much astir conditional constructs successful Bash for additional speechmaking. Besides, research however to usage exit codes successful ammunition scripts for amended mistake direction, and see speechmaking astir champion practices for ammunition scripting kind to compose maintainable scripts.


Previous Post Next Post

Formulario de contacto