Skip to content
Advertisement

Amazon CLI bash script on Ubuntu 16.04, “unexpected operator” on if statements (syntax looks correct)

I’m trying to troubleshoot issues I’m having with an Amazon CLI backup script that’s running on Ubuntu Server 16.04.

When I run the script manually I see that my if statements throw errors. Per request I’ve reduced my example to be minimal and verifiable. This script was running on another production server just fine. I’ve also run it through a shell syntax checker, from what I can see the syntax looks correct. What am I missing?

Also, the syntax checker wanted me to wrap all of my variables in double quotes. Why?

Error:

backup.sh: 34: [: Friday: unexpected operator

Example:

#!/bin/bash

################
# User Settings:
################

    # your AWS bucket name
    aws_bucket="s3://mybucket"

    # your server path to AWS
    aws_path="/usr/bin/aws"

    weekly_backup_day="Friday"

    # the (2 digit?) date you want your monthly backup run
    monthly_backup_date="01"

################
# Set Date Variables
################

dayOfWeek="$(date +'%A')"
monthNumber=$(date + '%m')
dateOfMonth=$(date '+%d')

################
# Run Weekly
################

if [ $# -lt 1 ] && [ "$dayOfWeek" == "$weekly_backup_day" ] ; then

    echo "Running Weekly"
    $aws_path s3 sync "$aws_bucket"/daily/"$dayOfWeek" "$aws_bucket"/weekly/"$dateOfMonth" --delete

fi

Advertisement

Answer

This breaks:

monthNumber=$(date + '%m')

it has to be

monthNumber=$(date +'%m')

but I suspect it’s just a typo as it would prevent your error message from appearing.

You are probably running this as follows:

sh ./backup.sh

which means that the #!/bin/bash line is ignored, and either Bash in POSIX mode or another shell altogether is run. == is not POSIX, so you have to change

if [ $# -lt 1 ] && [ "$dayOfWeek" == "$weekly_backup_day" ]

to

if [ $# -lt 1 ] && [ "$dayOfWeek" = "$weekly_backup_day" ]

or run it with

bash ./backup.sh

or just

./backup.sh

Consider:

$ sh -c '[ 1 == 1 ] && echo Yes'      # Can't have "==" in sh
sh: 1: [: 1: unexpected operator
$ sh -c '[ 1 = 1 ] && echo Yes'       # "=" is okay
Yes
$ bash -c '[ 1 == 1 ] && echo Yes'    # Bash does not care either way
Yes
$ bash -c '[ 1 = 1 ] && echo Yes'
Yes
$ bash -c '(( 1 == 1 )) && echo Yes'  # (( )) is a Bashism
Yes

As for “why quote”, the summary is “because of word splitting and glob expansion”. The Wooledge wiki has a good article about it.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement