The If Else comparsion throws weired error [duplicate] - bash

This question already has answers here:
Why should there be spaces around '[' and ']' in Bash?
(5 answers)
Closed 8 months ago.
Unable to run code, error "[[Add:" not found.
#!/bin/bash
add() {
first="${1}"
second="${2}"
result=`expr $first + $second`
echo "The sum of two numbers are $result"
return $result
}
subtract() {
first="${1}"
second="${2}"
result=`expr $first - $second`
echo "The sum of two numbers are $result"
return $result
}
echo "[0] Add"
echo "[1] Subtract"
read operation
echo "Enter Number One"
read first
echo "Enter Number Two"
read second
if [["$operation" == "Add"]]
then
add $first $second
else
subtract $first $second
fi
I am trying to run this code, the if else comparison does not work. Each time i execute the code, at line 32 an error is occurred and else is executed. I am trying to create an addition/subtraction bash sh file.
root#Kumaraswamy:~# ./maths.sh
[0] Add
[1] Subtract
Add
Enter Number One
7
Enter Number Two
3
./maths.sh: line 32: [[Add: command not found
The sum of two numbers are 4
root#Kumaraswamy:~#

Leave a space after [ or [[. That should work since these are real executables found in one of the directories listed under environment variable $PATH.

Related

How to only accept input that is a valid index of an array in bash [duplicate]

This question already has answers here:
Why should there be spaces around '[' and ']' in Bash?
(5 answers)
Difference between single and double square brackets in Bash
(7 answers)
Why is "[[ 10 < 2 ]]" true when comparing numbers in bash? [duplicate]
(1 answer)
Closed 6 months ago.
I am trying some simple input validation in bash. Basically this part of my script outputs "press [index] to select [array element]." However I cannot seem to get it to stop and exit gracefully when an invalid input is entered. From my research so far this SHOULD work:
declare -a scenarios=()
scenarios+=("Scenario_123")
scenarios+=("Scenario_456")
scenarios+=("Scenario_789")
for i in ${!scenarios[#]}; do
echo -e "select $i for ${scenarios[$i]}"
done
read ScenInd
echo ${#scenarios[#]} #[${ScenInd}=~^[0-9]+$, =~ ^[[:digit:]]+
if ! [${ScenInd}=~ ^[[:digit:]]+$ ] || [${ScenInd} < 0] || [${ScenInd} >= ${#scenarios[#]}];
then
echo "INVALID SELECTION"
exit
fi
but when I run it and enter 8, I get '[8=~: command not found'
What have I done wrong and how do I fix this? I have tried this both with [${ScenInd}=~^[0-9]+$ and =~ ^[[:digit:]]+ yet the results are the same.
Thanks in advance

How can I check if a variable that need to contain a number has been set? [duplicate]

This question already has answers here:
How do I test if a variable is a number in Bash?
(40 answers)
How to check if a variable is set in Bash
(38 answers)
Closed 4 years ago.
Given the following code:
Max=
if [[ something exists.. ]]; then
Max=2
// .. more code that can changes the value of Max
fi
// HERE
How can I check at "HERE" if Max is equal to some number (setted)?
if [ -z "$Max" ]
then
echo "Max: not set"
else if [ $Max -eq some_number ]
then
echo "Max is equal to some number"
else
echo "Max is set but not equal to some number"
fi
or
if [ -n "$Max" -a "$Max" = "some_number" ]
...
Notice that the second example is doing a string comparison which can solve some headaches but may hurt the sensibilities of purists.
Cool !
Max is set by default to an empty value, that when used in an arithmetic context, returns zero. For example:
Try running echo $(( definitelyNotAGivenName)) it comes out as zero, cool!
You can use the round brackets for arithmetic comparing - see more here and here

Why does if condition give error in bash? [duplicate]

This question already has answers here:
Getting "command not found" error while comparing two strings in Bash
(4 answers)
Closed 6 years ago.
My code below:
echo "====================================="
echo " Test Programme "
echo "====================================="
echo
read -p "Enter Name: " name
if [$name -eq ""]; then
sleep 1
echo "Oh Great! You haven't entered name."
exit
fi
read -p "Enter age: " age
According to that code,I expected "Oh Great! You haven't entered name." to show up when user skips entering the name which WORKS WELL
But, when you enter a proper string for name, it gives this message/ error:
./cool_ham.sh: line 13: [Franco: command not found
I want to know the reason for that.
I have even tried "$name" = "" after #Jack suggested, but still din't work .
Put a space between the square braces of your if condition and its contents.
if [ "$name" = "" ]; then
Additionally note that I use = over -eq to compare strings. -eq is used to compare integer values, while = will compare strings, which can be unintuitive coming from other languages.
I also quoted $name to prevent globbing and word splitting.

input vs variable comparison isn't working? [duplicate]

This question already has answers here:
How do I compare two string variables in an 'if' statement in Bash? [duplicate]
(12 answers)
Closed 6 years ago.
Here is a random number generator followed by a line clear timer and you are then to try and input the number that you saw. I cant seem to set up the comparison between the randNum variable and the input. I tried setting a defined value for the input as well and still receive an error "command not found" when checking input vs randNum variable
n=$RANDOM$RANDOM$RANDOM; let "n %= 10000000000";
echo $n
for i in {5..1}; do echo $i; sleep 1; tput cuu1; tput el; done
tput cuu1; tput el
echo "what was that number?"
#read input
input=999999999
if [$input == $n]
then
echo "you are correct"
else
echo "you are incorrect"
fi
Shells need spaces around brackets [ and ] when used for this purpose (replacement syntax for the test command), and you should better use -eq instead of == for numeric comparison:
if [ $input -eq $n ]
If you use the arithmetic comparison, rather than the old testcommand (a.k.a. [) then you can avoid these issues. Spaces here are less important inside the brackets:
if (( input == n ))
Note that the leading $ is not required (and using it can cause issues)

Bash - Get first 3 letters of filename [duplicate]

This question already has answers here:
Extract substring in Bash
(26 answers)
Closed 8 years ago.
I have a little bash script and have $file and $file2 variable. This is file and I want to get first 3 letters of this file name. And I want to compare them:
I tried:
curfile=$(basename $file)
curfilefirst3=${curfile:0:3}
curfile2=$(basename $file2)
curfile2first3=${curfile2:0:3}
if ((curfilefirst3 == curfile2first3 )); then
....
But I think have problems, how can I fix?
Thank you.
You're missing $ for the strings in the comparison and you'll need to wrap each string with " and the entire expression with []:
file="this.txt"
file2="that.txt"
curfile=$(basename $file)
curfilefirst3=${curfile:0:3}
curfile2=$(basename $file2)
curfile2first3=${curfile2:0:3}
echo $curfile2first3
echo $curfilefirst3
if [ "$curfile2first3" == "$curfilefirst3" ]
then
echo "same!"
else
echo "different!"
fi
It might be a good idea to read up on bash conditionals
Substring Extraction
${string:position} Extracts substring from $string at $position.
However, if should use [ and not ( as in:
if [ $curfilefirst3 == $curfile2first3 ]; then
The corrected version:
#!/bin/bash
file=abcdef
file2=abc123456
curfile=$(basename $file)
curfilefirst3=${curfile:0:3}
curfile2=$(basename $file2)
curfile2first3=${curfile2:0:3}
echo $curfilefirst3
echo $curfile2first3
if [ $curfilefirst3 = $curfile2first3 ]; then
echo same
else
echo different
fi
It prints same
So, works

Resources