比较Shell脚本中的两个数字 [英] Compare two numbers in shell script
问题描述
编写一个Bash shell脚本"order.sh",该脚本接受两个整数参数"a"和"b",并打印出适当的关系"a<b","a == b"或"a> b"(用"a"和"b"的值替换).
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).
代码:
#!/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
我无法编译他的代码,因为它失败并说"/bin/sh:找不到命令"有人可以告诉我这是什么意思吗?我是Shell脚本的新手,也不知道是什么问题...
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...
推荐答案
我无法编译他的代码,因为它失败并说"/bin/sh:找不到命令",有人可以告诉我这是什么意思吗?我是Shell脚本的新手,也不知道是什么问题...
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...
该声明中的几个问题:
- 编译此代码" ...无需编译Bash脚本.Bash是一种解释性语言
- "/bin/sh:找不到make命令"表示的样子完全相同:找不到
make
命令.您在PATH
上没有make
命令.但这没关系,因为您不需要在此处make
- "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 amake
command on yourPATH
. But it doesn't matter, because you don't needmake
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" ]
其他问题:
- 在3种情况下不使用
if-elif-else
- 破损的条件:有2个
if
,但只有1个结束的fi
- Not using
if-elif-else
for the 3 cases - Broken conditions: there are 2
if
but only 1 closingfi
其他一些提示:
- 要使用Bash进行算术运算,请使用
((...))
而不是[...]
. - 代替
echo -n;read
,请使用read -p
:这是一个命令,而不是两个命令,并且echo
的标志不是可移植的,因此最好避免使用它们 - 缩进
if-elif-else
的内容,以使脚本更易于阅读
- For doing arithmetic in Bash, use
((...))
instead of[...]
. - Instead of
echo -n; read
, useread -p
: it's one command instead of two, and the flags ofecho
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
应用了更正和改进后:
#!/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
这篇关于比较Shell脚本中的两个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!