GNU/Linux >> Linux Esercitazione >  >> Linux

Come usare i booleani nel guscio di pesce?

Sono passato a fish shell e abbastanza soddisfatto. Non ho capito come posso gestire i booleani. Sono riuscito a scrivere config.fish che esegue tmux su ssh (vedi:Come posso avviare automaticamente tmux in fish shell durante la connessione al server remoto tramite ssh) ma non sono soddisfatto della leggibilità del codice e voglio saperne di più su fish shell (ho già letto il tutorial e ho esaminato il riferimento). Voglio che il codice assomigli a questo (so che la sintassi non è corretta, voglio solo mostrare l'idea):

set PPID (ps --pid %self -o ppid --no-headers) 
if ps --pid $PPID | grep ssh 
    set attached (tmux has-session -t remote; and tmux attach-session -t remote) 
    if not attached 
        set created (tmux new-session -s remote; and kill %self) 
    end 
    if !(test attached -o created) 
        echo "tmux failed to start; using plain fish shell" 
    end 
end

So che posso memorizzare $status es e confrontarli con test come numeri interi ma penso che sia brutto e ancora più illeggibile. Quindi il problema è riutilizzare $status es e usali in if e test .

Come posso ottenere qualcosa del genere?

Risposta accettata:

Puoi strutturarlo come una catena if/else. È possibile (anche se poco maneggevole) utilizzare begin/end per inserire un'istruzione composta come condizione if:

if begin ; tmux has-session -t remote; and tmux attach-session -t remote; end
    # We're attached!
else if begin; tmux new-session -s remote; and kill %self; end
    # We created a new session
else
    echo "tmux failed to start; using plain fish shell"
end

Uno stile più gradevole sono i modificatori booleani. inizio/fine sostituiscono le parentesi:

begin
    tmux has-session -t remote
    and tmux attach-session -t remote
end
or begin
    tmux new-session -s remote
    and kill %self
end
or echo "tmux failed to start; using plain fish shell"

(Il primo inizio/fine non è strettamente necessario, ma migliora la chiarezza IMO.)

Il factoring delle funzioni è una terza possibilità:

function tmux_attach
    tmux has-session -t remote
    and tmux attach-session -t remote
end

function tmux_new_session
    tmux new-session -s remote
    and kill %self
end

tmux_attach
or tmux_new_session
or echo "tmux failed to start; using plain fish shell"

Linux
  1. Come utilizzare il comando Linux Rsync (sincronizzazione remota).

  2. Come usare Tmux + Cheat Sheet

  3. Come usare gli alias di shell in Linux

  4. Come usare il comando su su adb shell?

  5. Come recuperare una shell dopo una disconnessione

Come installare e utilizzare ZSH Shell in Linux

Come utilizzare le estensioni della shell di GNOME [Guida completa]

Come utilizzare SSH per connettersi a un server remoto

Come installare e utilizzare Nu Shell su Linux

Come utilizzare if-else negli script della shell?

Come utilizzare Linux Bash Shell in Windows 10?