Sunday, May 5, 2024
9
rated 0 times [  9] [ 0]  / answers: 1 / hits: 1773  / 2 Years ago, tue, february 1, 2022, 1:19:21

I wrote this simple script it works too but shows an error



clear
echo Enter 1st number
read n1
echo Enter 2nd number
read n2
echo MUlti is `expr $n1 * $n2`;
if [$n1 -lt $n2]
then
echo $n1 'is bigger than' $n2
else
echo $n2 'is bigger than' $n1
fi


output



Enter 1st number
5
Enter 2nd number
10
MUlti is 50
./script.sh: line 7: [5: command not found
10 is bigger than 5

More From » command-line

 Answers
2

The [ is a command builtin, also known as test, and as all commands requires at least a space to separate it from other words in the command. [ is also available as a regular command in /usr/bin/[ or /usr/bin/test.



The presence of a final ] is instead a requirement of the command, when invoked as [, and the spaces around it are required as for every parameter of a command.



That said, in bash you should use the command [[, that has some avantages over [, like for example supporting && and || for logical operations, beside -a and -o.



Moreover, to do integer arithmetic operations and comparison between integers it is better to use arithmetic expansions $((math operations)), and the corresponding command ((math ops)).



With these observations, your script could be:



#!/bin/bash

clear
echo "Enter 1st number"
read n1
echo "Enter 2nd number"
read n2
echo "Multi is $((n1 * n2))"
if ((n1 > n2)); then
echo "$n1 is bigger than $n2"
else
echo "$n2 is bigger than $n1"
fi


Remember to make it executable (chmod +x my-script), then execute it with ./my-script.


[#43817] Wednesday, February 2, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
damomnning

Total Points: 422
Total Questions: 90
Total Answers: 106

Location: Mali
Member since Thu, Aug 13, 2020
4 Years ago
damomnning questions
;