Score:0

Bash from scratch --again

cn flag

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!

terdon avatar
cn flag
How do you run this? First of all, you cannot get the error you mention since you don't have `!=` anywhere in your script. Second, you're missing the closing `if` which means you would get yet another error. Third, you are probably running the script without an argument so `$1` is undefined. But please don't make us guess: [edit] your question and make sure you show the actual code you use, explain how you launch it and the actual errors you get.
Score:2
cn flag
raj

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
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.