Fish Shell でブール値を使用するにはどうすればいいですか?

Fish Shell でブール値を使用するにはどうすればいいですか?

私はシェルに切り替えましたfishが、かなり満足しています。ブール値をどのように処理すればよいのかわかりませんでした。実行するコードを書くことができました(config.fish参照:tmuxsshSSH経由でリモートサーバーに接続しているときに、fish shellでtmuxを自動的に起動するにはどうすればよいですか) 接続ですが、コードの読みやすさに満足しておらず、シェルについてさらに学びたいと思っていますfish(すでにチュートリアルを読み、リファレンスを確認しました)。コードは次のようになります (構文が正しくないことはわかっていますが、アイデアを示したいだけです)。

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

$statuses を保存して整数として と比較できることはわかっていますtestが、見た目が悪く、さらに読みにくいと思います。問題は、$statuses を再利用して および で使用することifですtest

どうすればこのようなことを実現できるでしょうか?

答え1

これを if/else チェーンとして構造化できます。begin/end を使用して複合ステートメントを 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

よりよいスタイルはブール修飾子です。begin/end は括弧の代わりになります。

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"

(最初の begin/end は厳密には必要ではありませんが、明確さが向上すると私は考えています。)

関数を因数分解することは 3 番目の可能性です。

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"

関連情報