2

I used the have the following tmux shortcut function defined in a separate script and aliased, which worked fine but was messy. I decided to move it to my .zshrc where it naturally belongs, and encountered a problem I wasn't able to figure out.

function t () {re='^[0-9]+$'
if [ "$1" == "kill" ]
then
        tmux kill-session -t $2
elif [[ "$1" =~ "$re" ]]
then
        tmux attach-session -d -t $1
fi}

I source my .zshrc, call the function, and get:

t:1: = not found

I know the function is defined:

╭─bennett@Io [~] using
╰─○ which t
t () {
    re='^[0-9]+$'
    if [ "$1" == "kill" ]
    then
            tmux kill-session -t $2
    elif [[ "$1" =~ "$re" ]]
    then
            tmux attach-session -d -t $1
    fi
}

I'm assuming this is complaining about the first line of the function. I've tried shifting the first line of the function down several lines, which doesn't change anything except which line the error message refers to. Any clue what's going on? I haven't found anything relating to this specific issue on SO.

Bennett Talpers
  • 802
  • 6
  • 9

2 Answers2

9

The command [ (or test) only supports a single = to check for equality of two strings. Using == will result in a "= not found" error message. (See man 1 test)

zsh has the [ builtin mainly for compatibility reasons. It tries to implement POSIX where possible, with all the quirks this may bring (See the Zsh Manual).

Unless you need a script to be POSIX compliant (e.g. for compatibility with other shells), I would strongly suggest to use conditional expressions, that is [[ ... ]], instead of [ ... ]. It has more features, does not require quotes or other workarounds for possibly empty values and even allows to use arithmetic expressions.

Adaephon
  • 16,929
  • 1
  • 54
  • 71
0

Wrapping the first conditional in a second set of square-brackets seemed to resolve the issue.

More information on single vs double brackets here: Is [[ ]] preferable over [ ] in bash scripts?

Bennett Talpers
  • 802
  • 6
  • 9