Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script if statement [: unexpected operator [closed]

I am trying to create a very simple shell script which detects if it's being run as root. For some reason, the code below produces a Error: [: stackunderflow: unexpected operator on line 6, I have no idea why? I have this working on a bash script but for portability and some education, I wanted to do this with a shell script.

#!/bin/sh
##
# Check for root launch
#
set -e
USER="$(id -un 2>/dev/null || true)"
if [ "$USER" == 'root' ]; then
    echo "You must be a root user"
    exit 1
else
    echo 'Not root!'
    exit 0
fi

This is being run as ./check.sh from a Debian Jessie amd64 desktop.

like image 240
stackunderflow Avatar asked Sep 09 '26 15:09

stackunderflow


1 Answers

First, you have this tagged as bash, and it's bourne. As sigmalha pointed out, you are using the wrong operator. Use = instead of ==.

In addition, you are failing (exit 1) on a success, and succeeding (exit 0) on your failure.

like image 144
SaintHax Avatar answered Sep 11 '26 10:09

SaintHax



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!