【问题标题】:Compare two numbers in shell script [duplicate]比较shell脚本中的两个数字[重复]
【发布时间】:2016-01-16 14:25:59
【问题描述】:

编写一个 Bash shell 脚本“order.sh”,它接受两个整数参数“a”和“b”,并打印出适当的关系“a b” (将“a”和“b”替换为它们的值)。

代码:

#!/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: make command not found” 有人能告诉我这是什么意思吗?我是 shell 脚本的新手,我不知道是什么问题...

【问题讨论】:

  • 试试whereis bash 命令
  • www.shellcheck.net/ 是你的朋友。在其他问题中,您会发现在[ 之后和] 之前需要一个空格
  • MO,当某些东西在 bash 中不起作用时,您可以通过使用 bash -x scriptname 调用您的脚本来启用调试输出。除了您必须看到的正常错误之外,它还会逐行显示打印到stdout(屏幕)的脚本的操作。如果由于某种原因 bash 不在您的 PATH 中,那么它通常在 /usr/bin/bash 中(在大多数 unix/linux 类型系统上)。如果您在 windows 上使用mingw/msys,请阅读mingw 安装说明以设置路径和环境。你在什么操作系统上运行?

标签: bash shell


【解决方案1】:

您可能应该使用/usr/bin/env 来查找bash。我认为您还想要一个elif(和一个else - 您当前的一个缺少fi 并且不会测试大于),您应该使用[[]](也是您错过了echo"$y &lt; $x" 的空格)。类似的,

#!/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

我进行了测试,并按照您的预期进行。我建议你看看7.02. More advanced if usage - Bash Beginner's Guide

【讨论】:

  • 为什么不用read -p 而不是echo; read
  • @BenjaminW。 read -p 和 read x 有什么区别?
  • read -p "Enter something: " line 提供提示字符串;它与echo -n "Enter something: "; read line 几乎相同,但仅在一个语句中,并且仅当输入来自终端时才会显示提示(请参阅the manual)。
【解决方案2】:

我无法编译他的代码,因为它失败并说“/bin/sh: make command not found”有人能告诉我这是什么意思吗?我是 shell 脚本的新手,我不知道是什么问题...

该声明中有几个问题:

  • "compile this code" ... 不需要编译 Bash 脚本。 Bash 是一种解释型语言
  • “/bin/sh: make command not found”的意思就是它的样子:找不到make 命令。你的PATH 上没有make 命令。不过没关系,因为这里不需要make

您的脚本有语法错误,例如:

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

您需要在[] 之前放置一个空格,如下所示:

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

其他问题:

  • 这 3 种情况没有使用 if-elif-else
  • 破碎条件:有2个if但只有1个关闭fi

其他一些提示:

  • 要在 Bash 中进行算术运算,请使用 ((...)) 而不是 [...]
  • 不要使用echo -n; read,而是使用read -p:这是一个命令而不是两个命令,并且echo 的标志不可移植,因此最好避免使用它们
  • 缩进if-elif-else的内容,使脚本更易于阅读

应用了更正和改进:

#!/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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-28
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 2015-12-03
    • 1970-01-01
    相关资源
    最近更新 更多