Home > Blockchain >  Why is my zshrc function not working when adding arguments?
Why is my zshrc function not working when adding arguments?

Time:08-19

I am trying to make a function to start, stop or restart from any directory The code works fine without any arguments but when adding any argument I get the webserver:6: = not found error, when testing the variables everything looks like it should work

function webserver {
    #echo $USERNAME
    'echo $1
    if [ "$1" != "" ]
    then

        if [ "$1" == "start"]
        then
            /Users/$USERNAME/start.sh
        fi
        
        if [ "$1" == "stop"]
        then
            /Users/$USERNAME/stop.sh
        fi

        if [ "$1" == "restart"]
        then
            /Users/$USERNAME/restart.sh
        fi

    else
        echo "Invalid arguments! Valid arguments are : start stop restart"
    fi
}

Why is this code not working?

CodePudding user response:

There's a single-quote before the echo $1 command, which'll cause different trouble. Is that a typo?

The mains problem is that your comparison syntax is wrong; in a [ ] test, use a single = for string equality test, and you need spaces between each syntactic element, including before the final ].

if [ "$1" == "start"]    # Bad, will give errors
if [ "$1" = "start" ]    # Good, will work as expected

Also, I'd replace that series of if statements with a either a case statement, or a single if ... elif ... elif, since only one branch will ever be taken.

case "$1" in
    start)
        /Users/$USERNAME/start.sh ;;
    
    stop)
        /Users/$USERNAME/stop.sh ;;

    restart)
        /Users/$USERNAME/restart.sh ;;

    *)  # This is the case equivalent of "else"
        echo "Invalid arguments! Valid arguments are : start stop restart" ;;
esac

CodePudding user response:

like Gordon said, the syntax for zsh is wrong with only one [ ].

according to "==" logical operator and zsh version 5.7.x (installed using Homebrew)

Simple answer: a == is a logical operator only inside [[ … ]] constructs. And it works also in ksh and bash.

When used outside a [[ … ]] construct a =cmd becomes a filename expansion operator but only in zsh

$ echo ==
zsh: = not found
  • Related