Compare two numbers in shell script [duplicate]

2019-09-02 20:02发布

问题:

This question already has an answer here:

  • Comparing numbers in Bash 7 answers

Write a Bash shell script “order.sh” that takes two integer arguments “a” and “b”, and prints out the appropriate relationship “a < b”, “a == b” or “a > b” (with “a” and “b” replaced by their values).

code:

#!/bin/bash
echo -n "enter the first number:"; read x
echo -n " enter the second number:"; read y

if ["$x " -lt "$y"]
then
echo "$x < $y"
else
echo"$y < $x"

if [ "$x" -eq "$y"]
then
echo " $x == $y "

fi 

i am not being able to compile his code as it is failing and says "/bin/sh: make command not found" can someone tell me what this means? i am new to shell scripting and i have no idea what is the problem...

回答1:

i am not being able to compile his code as it is failing and says "/bin/sh: make command not found" can someone tell me what this means? i am new to shell scripting and i have no idea what is the problem...

Several problems in that statement:

  • "compile this code" ... a Bash script doesn't need to be compiled. Bash is an interpreted language
  • "/bin/sh: make command not found" means exactly what it looks like: the make command is not found. You don't have a make command on your PATH. But it doesn't matter, because you don't need make here

Your script has syntax errors, for example:

if ["$x " -lt "$y"]

You need to put a space after [ and before ], like this:

if [ "$x " -lt "$y" ]

Other problems:

  • Not using if-elif-else for the 3 cases
  • Broken conditions: there are 2 if but only 1 closing fi

A few other tips:

  • For doing arithmetic in Bash, use ((...)) instead of [...].
  • Instead of echo -n; read, use read -p: it's one command instead of two, and the flags of echo are not portable, so it's better to avoid using them
  • Indent the content of if-elif-else to make the script easier to read

With the corrections and improvements applied:

#!/usr/bin/env bash

read -p "enter the first number: "
read -p "enter the second number: "

if ((x < y)); then
    echo "$x < $y"
elif ((x > y)); then
    echo "$y < $x"
else
    echo "$x == $y"
fi


回答2:

You should probably use /usr/bin/env to find bash. I think you also wanted an elif (and an else - your current one is missing a fi and won't test for greater than), and you should be using [[ and ]] (also you missed a space with echo"$y < $x"). Something like,

#!/usr/bin/env bash

echo -n "enter the first number:"; read x
echo -n "enter the second number:"; read y
if [[ "$x" -lt "$y" ]]; then
        echo "$x < $y"
elif [[ "$x" -gt "$y" ]]; then
        echo "$y < $x"
else
        echo "$x == $y"
fi

Which I tested, and does as you would expect. I suggest you see 7.02. More advanced if usage - Bash Beginner's Guide



标签: bash shell