0

As my journey through Bash goes on, I'm still stuck on ridiculous stuff such as this script I just can't wrap my head around on:

#!/bin/bash

if [ $1 -gt 100 ] then echo "You typed a larger number" if (( $1 % 2 == 0 )) then echo "And it's even an even number" fi

Recently I was recommended to keep ShellCheck at hand's reach, and so I did, but it seems like its suggestions on how to improve this script doesn't work out either. Basically when I try to run it, I always get errors like "[: !=: unary operator expected" even when I try to quote $1 into "$1", which is also recommended by ShellCheck. Could anyone help me down? Thanks a lot in advance!

1 Answers1

2

Your script has a syntax error; it lacks one more fi at the end. Once this error is fixed, you get the "unary operator expected", because your $1 value (the value of the first parameter of the script) is empty, and the first if command expects that value to be non-empty. You must call the script with some number as a parameter, like:

./script 150

Then you get the response:

You typed a larger number
And it's even an even number

If you want the script to not display error messages when called with no parameter, before using the parameter you must detect whether the parameter is empty and do something. For example you can add the following code before your first if command:

if [ -z "$1" ]
then
   echo "Parameter required!"
   exit
fi
raj
  • 11,409