简体   繁体   中英

Syntax error near unexpected token 'elif' in Bash

I'm using a new language, I think it's linux but to be honest I have no clue; we're connecting to some server through a program called putty to do this programming. As part of an assignment I have to create a calculator program that takes two numbers and an operator as arugments but I'm getting a bunch of unexpected token errors. I'm very lost and neither my text no my professor is helpful so far

#!/bin/bash

function add {
        echo $(( $1 + $2 ))
}

function subtract {
        echo $(( $1 - $2 ))
}

function multiply {
        echo $(( $1 x $2 ))
}

function divide {
        echo $(( $1 / $2 ))
}

if [ $3 = '+' ] then add

so far I'm just trying to get it so I can get 2 from the command ./calc.sh 1 1 + but I keep getting unexpected token error on line 20 syntax error near unexpected token 'elif' [ $3 = '-' ] then subtract

This will do what you want:

#!/bin/bash

function add {
        echo $(( $1 + $2 ))
}

if [ $3 = '+' ]; then add $1 $2
fi

There are a number of issues in just what we can see, in the last visible line.

You need either a line break or a semi colon after if [ $3 = '+' ] And while it is possible that it is just where it chose to stop pasting, your functions need to be passed arguments, so "add $1 $2" vs "add"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM