Posso fare in modo che tutti i comandi abbiano un feedback se hanno funzionato o no?


11

A volte quando eseguo i comandi non viene visualizzato un output, quindi non sono sicuro che abbiano funzionato o meno. È possibile inviare feedback a tutti i comandi se sono stati eseguiti correttamente o no? O come minimo per visualizzare l'id di feedback che hanno eseguito (correttamente o no)


6
L'idea generale è: nessun feedback significa che ha funzionato.
Rinzwind,

1
Questo non è esattamente vero. Ad esempio, cryptsetupper impostazione predefinita è possibile saltare alcuni messaggi di errore. È una buona cosa avere $?nel tuo PS1. Il prossimo passo è aggiungere anche l'ora corrente, per conoscere sempre i tempi dei comandi;)
d33tah

Risposte:


11

(Penso che dal momento che stai postando all'interno di Ask Ubuntu possiamo presumere che tu stia parlando della shell predefinita, cioè Bash .)

C'è una risposta molto buona nella domanda Stack Overflow In uno script di shell: i comandi della shell echo mentre vengono eseguiti (questa non è solo una soluzione specifica di Ubuntu).

Quello che devi fare è usare il comando set per attivare verbose o xtrace.

set -o

vi darà un elenco di quali parametri correnti vengono commutati on o off .

set -v

o la versione longform:

set -o verbose

si accende verbose ON .

Penso che ciò che vuoi, in realtà, sia xtrace. Questo non solo farà eco ad ogni comando che esegui, ma espanderà anche i parametri e ti darà più feedback. Quindi, se faccio qualcosa di stupido come digitare "ciao" al terminale, otterrò l'eco di ciò che ho digitato e un rapporto / traccia di ciò che la shell ha fatto per tentare di eseguire il comando "ciao" (vedi screenshot sotto ):

Inserisci qui la descrizione dell'immagine

Per abilitare xtrace:

set -x

o:

set -o xtrace

Per disabilitare questi parametri, è necessario (in modo intuitivo) chiamare gli stessi comandi tranne con un simbolo più + anziché un trattino o un simbolo meno, quindi, ad esempio:

set +v

si trasformerà verbose OFF , simile:

set +x

si trasformerà xtrace OFF .


Una guida dettagliata sulle opzioni della shell è contenuta nel Capitolo 33. Opzioni, Guida avanzata di script Bash .


1
Ma come funziona quando il comando è corretto? dà qualche risultato? dire per il comando whoami >/dev/null.
Utente registrato

Sì, certo che lo fa, fa eco a ciò che hai digitato più eventuali parametri aggiuntivi coinvolti nel comando che sono stati chiamati silenziosamente quando hai invocato il tuo comando. Se vuoi dire, stampa "SUCCESSO", ma purtroppo no, la risposta di Avinash Raj lo farà.
Benjamin R

@PeterMortensen grazie per le belle modifiche sottili sulla mia risposta.
Benjamin R,

13

Per verificare se alcuni comandi hanno funzionato correttamente oppure no, è possibile verificare lo stato di ritorno , dato da $?, del comando precedente con:

echo $?

Uno stato di ritorno 0indica che il comando è stato completato correttamente, mentre un output diverso da zero ( codice di errore ) significherebbe che si sono verificati alcuni problemi o c'è un errore e la categoria può essere conosciuta dal codice di errore. I codici di errore Linux / C sono definiti in /usr/include/asm-generic/errno-base.he /usr/include/asm-generic/errno.h.

Anche in bash, .bashrcdefinisce un alias alertche può essere usato per notificare con lo stato di completamento. Dovresti collegare l'alias con il comando o il comando combo in questo modo:

some_command --some-switch; alert

È possibile aggiungere la seguente riga di codice al ~/.bashrcfile per visualizzare lo stato di ritorno dell'ultimo comando eseguito.

# show the return code of last command executed
PS1='${debian_chroot:+($debian_chroot)}\u@\h(lst ret. $(echo $?) ):\w\$ '

(apri il file ~/.bashrccon l'editor di testo che preferisci e copia la riga sopra, incollalo nel file e salva. Avvia una nuova istanza del terminale e dovresti averlo in azione. Oppure potresti definire alcune funzioni e usare con PS1come come illustrato di seguito.)

una piccola demo:

hash@precise(lst ret. 0 ):~$ ls -sh someFileThatsNotThere
ls: cannot access someFileThatsNotThere: No such file or directory
hash@precise(lst ret. 2 ):~$ 
hash@precise(lst ret. 2 ):~$ aCommandThatsNot
aCommandThatsNot: command not found
hash@precise(lst ret. 127 ):~$ 
hash@precise(lst ret. 127 ):~$ echo "you should get a lst ret. 0, I believe the system has echo installed :)"
you should get a lst ret. 0, I believe the system has echo installed :)
hash@precise(lst ret. 0 ):~$
hash@precise(lst ret. 0 ):~$ sudo touch /tmp/someTestFile
[sudo] password for hash: 
hash@precise(lst ret. 1 ):~$
hash@precise(lst ret. 1 ):~$ chown $USER:$USER /tmp/someTestFile 
chown: changing ownership of `/tmp/someTestFile': Operation not permitted

Solo giocando con PS1:) .. un po 'di più,

function showRetStat {
## line1: initiliazing retStat with the return status of the previous command
retStat=$?
## line2: Left padding the return status with spaces. If you prefer the unpadded one, you can just replace
# $retStatFtd in the lines initializing noErrStr and errStr among other possible ways.
retStatFtd=$(sed -e :a -e 's/^.\{1,2\}$/ &/;ta' <<< $retStat)
## lines3&4: Setting the strings to display for a successful and unsuccessful run of previous command
# which we are going to display with the prompt string. Change the strings to display text of your
# choice like you may set noErrStr="yippie!" , errStr="oopsie!" in place of what they're now.
noErrStr="retStat "$retStatFtd" :: PASS ^_^"
errStr="retStat "$retStatFtd" :: FAIL x_x"
## line5: Applying the logic and display the proper string at the prompt. Space padded number i.e. retStatFtd, here,
# worked in the logic, originally I intended to use this for the display while retStat in the conditional
# check; you could make the function one statement less if you want to.
echo "$([ $retStatFtd = 0 ] && echo "$noErrStr" || echo "$errStr")"
}

## Combining the function showRetStat into the prompt string.
PS1='${debian_chroot:+($debian_chroot)}\u@\h($(showRetStat)):\w\$ '

(puoi modificare la funzione per renderla più elegante, come fa @gronostaj nel suo post.)


2
Mi piace molto la tua risposta estesa con esempi. Sono abbastanza sicuro che OP voglia xtrace ma personalmente lo troverei utile per il debug dei miei programmi da riga di comando e per capire meglio gli altri.
Benjamin R

1
Suggerirei di riempire a sinistra il valore restituito, in modo che sia sempre della stessa lunghezza.
o0 '.

+1 per la modifica PS1. Questo è quello che uso, con il numero rosso in caso di errori, niente in più se l'ultimo comando ha avuto successo:\[\033[01;41;37m\]${?#0}\[\033[00;01;36m\] \u@\h:\w\[\033[00m\]\$
Carlos Campderrós

1
@rusty non è necessario il ~/.bashrcfile sorgente ?
Avinash Raj,

2
Sì, modificare PS1 è utile e molto flessibile. Mostro un ^_^successo felice e un altro rosso x_x.
Izkata,

5

È possibile modificare il prompt dei comandi per visualizzare un segno di spunta verde quando il comando precedente termina con 0 e X rossa altrimenti. Arch Linux Wiki ha un bel pezzo di codice da aggiungere al tuo bash.rc:

set_prompt () {
    Last_Command=$? # Must come first!
    Blue='\[\e[01;34m\]'
    White='\[\e[01;37m\]'
    Red='\[\e[01;31m\]'
    Green='\[\e[01;32m\]'
    Reset='\[\e[00m\]'
    FancyX='\342\234\227'
    Checkmark='\342\234\223'

    # Add a bright white exit status for the last command
    #PS1="$White\$? "
    # If it was successful, print a green check mark. Otherwise, print
    # a red X.
    if [[ $Last_Command == 0 ]]; then
        PS1+="$Green$Checkmark "
    else
        PS1+="$Red$FancyX "
    fi
    # If root, just print the host in red. Otherwise, print the current user
    # and host in green.
    if [[ $EUID == 0 ]]; then
        PS1+="$Red\\h "
    else
        PS1+="$Green\\u@\\h "
    fi
    # Print the working directory and prompt marker in blue, and reset
    # the text color to the default.
    PS1+="$Blue\\w \\\$$Reset "
}
PROMPT_COMMAND='set_prompt'

(Ho disabilitato il codice di errore effettivo perché non mi piace, se desideri vedere i codici esatti rimuovi semplicemente #da questa riga #PS1="$White\$? ":)

Ecco come appare:

Schermata del terminale della GUI

screenshot di tty


2

, è possibile ottenere feedback per ogni comando eseguito sul terminale. Funziona sulla base della echo $?quale restituisce 0 per un corretto completamento del comando e qualsiasi altro valore diverso da 0 per errore.

Per ottenere il feedback sull'esito positivo o negativo, aggiungi la riga seguente al ~/.bashrcfile.

bind 'RETURN: ";if [[ $? == 0 ]]; then tput setaf 6 && echo SUCCESS; tput sgr0; else tput setaf 1 && echo FAILURE; tput sgr0; fi;\n"' 

E quindi il ~/.bashrcfile sorgente per farlo funzionare.

source ~/.bashrc

Spiegazione:

Per ogni comando eseguito sul terminale, questo ;if [[ $? == 0 ]]; then tput setaf 6 && echo SUCCESS; tput sgr0; else tput setaf 1 && echo FAILURE; tput sgr0; fi;codice verrà automaticamente associato ad esso.

Esempio:

$ sudo apt-cache policy firefox;if [[ $? == 0 ]]; then tput setaf 6 && echo SUCCESS; tput sgr0; else tput setaf 1 && echo FAILURE; tput sgr0; fi;
firefox:
  Installed: 24.0+build1-0ubuntu1
  Candidate: 24.0+build1-0ubuntu1
  Version table:
 *** 24.0+build1-0ubuntu1 0
        500 http://ubuntu.inode.at/ubuntu/ saucy/main amd64 Packages
        100 /var/lib/dpkg/status
SUCCESS

$ suda apt-get update;if [[ $? == 0 ]]; then tput setaf 6 && echo SUCCESS; tput sgr0; else tput setaf 1 && echo FAILURE; tput sgr0; fi;
No command 'suda' found, did you mean:
 Command 'sudo' from package 'sudo-ldap' (universe)
 Command 'sudo' from package 'sudo' (main)
 suda: command not found
FAILURE

inserisci qui la descrizione dell'immagine


1
bind 'RETURN: " && echo SUCCESS || echo FAILED \n"'farà anche lo stesso, non è necessario controllare [[ $? == 0 ]]esplicitamente.
souravc

Tuttavia, lo standard C / Linux e la controparte standard grammaticale inglese in "Successo" sarebbero GUASTI.
Benjamin R
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.