Reputation: 189
I have the code below and am receiving the following error output:
Enter your exam score
40
./if2.sh: line 6: 40: No such file or directory
Very well done. You have an A grade.
I'm using bash 4.1.2(1) on CentOS.
#!/bin/bash
#This script demonstrates the if-then-elif format.
echo "Enter your exam score"
read exam_pct
if [ $exam_pct < 40 ]
then
echo "Sorry, you have failed."
elif [ $exam_pct > 70 ]
then
echo "Very well done. You have an A grade."
else
echo "Well done. You passed."
fi
What's wrong here?
Upvotes: 2
Views: 949
Reputation: 10917
Replace
if [ $exam_pct < 40 ]
with
if (( exam_pct < 40 ))
Take a look at the link given by Bill. Unix shell history is full of non-intuitive extensions. Depending on your case, Bash should be safe to use though. If you are interested in shell history take a look at http://www.in-ulm.de/~mascheck/bourne/
Upvotes: 4
Reputation: 69198
Just for completeness:
if [ $exam_pct \< 40 ]
also works
Upvotes: 1
Reputation: 27752
To elaborate on why you're getting the error you're getting: [
isn't special syntax; it's just an executable (usually provided through a builtin, though /usr/bin/[
probably exists on your system), which by convention takes "]" as its last argument.
So when you write [ $exam_pct < 40 ]
, what you're actually doing is starting [
with (ideally) two arguments (the contents of $exam_pct
, and ]
), and the contents of a file with the name 40
piped to its stdin.
Similarly, when you do [ $exam_pct > 70 ]
, you're redirecting the output of [ $exam_pct ]
(which will be blank, because [
doesn't ever write to stdout) to a file called 70
.
Upvotes: 3
Reputation: 5764
if [ $exam_pct < 40 ]
should be if [ "$exam_pct" -lt 40 ]
if [ $exam_pct > 70 ]
should be if [ "$exam_pct" -gt 70 ]
Please always quote your variables.
Look at this for more details - http://tldp.org/LDP/abs/html/comparison-ops.html
Upvotes: 4