Search code examples
zshzshrc

.zshrc unrecognized condition on $-


I'm attempting to port over some functionality from my old .bashrc into my .zshrc and I'm having trouble with a condition that worked in bash.

Whenever I remote log in to my computer, I had bash check the $- variable to see if it was interactive. If it was, I would start up an emacs server if one wasn't already running and change to my code directory. Otherwise (if I was getting a file with scp, for example), I wouldn't do anything.

Here's the bit of code:

if [[ $- -regex-match "i" ]]; then
    ps -u myusername | grep emacs > /dev/null
    if [ $? -eq 0 ]; then
        echo "emacs server already running"
    else
        emacsserver
    fi

    aliastocdtomydirectory
fi

And here's the error zsh gives me: .zshrc:125: unrecognized condition:$-'`

Does anyone know how to get around this error when using $- ? I've tried quoting it, wrapping it in $(echo $-) but none have worked. Thanks in advance.

Edit: If I switch my code to:

if [[ $- =~ "i" ]]; then
    ps -u myusername | grep emacs > /dev/null
    if [ $? -eq 0 ]; then
        echo "emacs server already running"
    else
        emacsserver
    fi

    aliastocdtomydirectory
fi

I now get: .zshrc:125: condition expected: =~ I'm not sure exactly what zsh is interpreting incorrectly here as I'm not very familiar with the semantics of zsh's shell scripts. Could someone point me in the right direction on how to express this condition in zsh?


Solution

  • In zsh, you don't need to bother with $-, which is--I think--intended primarily for POSIX compatibility.

    if [[ -o INTERACTIVE ]]; then
        if ps -u myusername | grep -q emacs; then
            echo "emacs server already running"
        else
            emacsserver
        fi
    
        aliastocdtomydirectory
    fi