4

I switched to fish shell and quite happy with it. I didn't get how can I handle booleans. I managed to write config.fish that executes tmux on ssh (see: How can I start tmux automatically in fish shell while connecting to remote server via ssh) connection but I'm not happy with code readability and want to learn more about fish shell (I've already read tutorial and looked through reference). I want code to look like that (I know that syntax isn't correct, I just want to show the 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

I know that I can store $statuses and compare them with test as integers but I think it's ugly and even more unreadable. So the problem is to reuse $statuses and use them in if and test.

How can I achieve something like this?

1 Answer 1

8

You can structure this as an if/else chain. It's possible (though unwieldy) to use begin/end to put a compound statement as an if condition:

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

A nicer style is boolean modifiers. begin/end take the place of parenthesis:

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"

(The first begin/end is not strictly necessary, but improves clarity IMO.)

Factoring out functions is a third possibility:

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"
1
  • 1
    Thank you! I tried to find solution that is exactly as in familiar languages and forgot about functions! I liked third variant the most because function names speak loud.
    – rominf
    Commented Mar 27, 2014 at 18:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .