How to use comparison in bash - bash

I'm trying to use comparison in bash, but just can't make it work.
#!/bin/bash
str="75.00 W, 170.00 W"
function str_check {
pow_array=()
regexp='([0-9]+)\.[0-9]+[[:space:]]W,[[:space:]]([0-9]+)\.[0-9]+[[:space:]]W'
[[ $str =~ $regexp ]] && for (( i = 0; i < 3; i++ )); do
pow_array+=("${BASH_REMATCH[$i]}")
done
if [ "$1" -lt ${pow_arr[1]} ]; then
echo "Available power limit is ${pow_array[0]}"
echo "Setting up ${pow_array[1]}"
elif [ "$1" -gt "${pow_arr[2]}" ]; then
echo "Available power limit is ${pow_array[0]}"
echo "Setting up ${pow_array[2]}"
else
echo "All good, setting up $1"
fi
}
str_check "70"
str_check "100"
str_check "200"
Already have tried '[[', '((' '[', qoute and unquote everething, but getting all kind of errors or wrong results. Need someone to give me a hand.
./t.sh: line 9: [: 70: unary operator expected
./t.sh: line 12: [: : integer expression expected

Time to discover shellcheck !
Line 9:
if [ "$1" -lt ${pow_arr[1]} ]; then
^-- SC2154: pow_arr is referenced but not assigned (did you mean 'pow_array'?).
^-- SC2086: Double quote to prevent globbing and word splitting.
Change all the references to pow_arr into pow_array and it works !

Related

Unexpected operator in if statement

In the following two lines I get this error?
What is wrong?
Debian Buster
my.sh: 101: [: !=: unexpected operator
my.sh: 103: [: !=: unexpected operator
if [ $CONTINUE != "y" ] && [ "$CONTINUE" != "n" ]; then
elif [ $CONTINUE = "n" ]; then
update
echo "\nContinue downloading? [y/n]"
read CONTINUE
# Error: Invalid argument
if [ $CONTINUE != "y" ] && [ $CONTINUE != "n" ]; then
error "Invalid argument"
elif [ $CONTINUE = "n" ]; then
echo "\nDonwload terminated!"
exit
fi
The script you’ve posted has various issues, which are highlighted by ShellCheck:
Line 1:
echo "\nContinue downloading? [y/n]"
^-- SC2028: echo may not expand escape sequences. Use printf.
Line 2:
read CONTINUE
^-- SC2162: read without -r will mangle backslashes.
Line 5:
if [ $CONTINUE != "y" ] && [ $CONTINUE != "n" ]; then
^-- SC2086: Double quote to prevent globbing and word splitting.
^-- SC2086: Double quote to prevent globbing and word splitting.
Did you mean: (apply this, apply all SC2086)
if [ "$CONTINUE" != "y" ] && [ "$CONTINUE" != "n" ]; then
Line 7:
elif [ $CONTINUE = "n" ]; then
^-- SC2086: Double quote to prevent globbing and word splitting.
Did you mean: (apply this, apply all SC2086)
elif [ "$CONTINUE" = "n" ]; then
Line 8:
echo "\nDonwload terminated!"
^-- SC2028: echo may not expand escape sequences. Use printf.
But despite these issues the script actually otherwise works as expected on Debian (Buster)’s default shell (which is dash). You might be running a non-default shell. The easiest way to solve your issue is therefore to
Declare a valid shebang line
Fix the issues highlighted above.
Which leaves us with this:
#!/bin/sh
printf "\nContinue downloading? [y/n] "
read -r CONTINUE
error() {
printf >&2 '%s\n' "$#"
exit 1
}
if [ "$CONTINUE" != y ] && [ "$CONTINUE" != n ]; then
error "Invalid argument"
elif [ "$CONTINUE" = n ]; then
printf "\nDownload terminated!\n"
exit
fi
(This also adds a definition for the undefined error call; substitute as appropriate.)

Comparing Numbers Two number in bash

I don't know where the problem is: when I execute this, I get an error:
./script.sh: line 4: if[ 7 -gt 5 ]: command not found
./script.sh: line 5: syntax error near unexpected token then'
./script.sh: line 5: `then'
#!/bin/bash
read a
read b
if[ $a -gt $b ]
then
echo "$a is greater than $b"
elif [ $a -lt $b ]
then
echo "$a is less than $b"
else
echo "$a is equal to $b"
fi
The syntax for if in bash follows:
if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi
Note the space following if; it is mandatory. Note also that [ isn't any kind of special syntax; it's just a command, same as ls or grep. You can't type ifgrep, so you can't type if[ either.
Because if[ is not if, you weren't in an if block, so then was unexpected, thus your syntax error.
Thus:
if [ "$a" -gt "$b" ] # Correct
not
if ["$a" -gt "$b" ] # Wrong because of lack of space
or
if[ $a -gt $b ] # Wrong because of lack of space and lack of quotes
(Leaving the quotes out leaves you open to a completely separate set of bugs).

if ["$i" -gt "$count"]; IS GIVING AN ERROR

I'm trying to put the 'f-$count'(f-1,f-2) name into the array.
Below is the code,
echo "Enter the count"
read count
echo $count
#arr=()
i=1
while true;
do
if ["$i" -gt "$count"]; then
exit 0
else
arr[$i]=f-$i
i=$((i+1))
fi
done
echo ${arr[#]}
I'm getting the error as 'script.sh: line 11: [3570: command not found
' continuously.
In shell programming, the brackets in the if MUST be delimited by spaces:
if ["$i" -gt "$count"]; then
MUST be:
if [ "$i" -gt "$count" ]; then
[EDIT] The left bracket ([) is actually a built-in shell command and so requires the space afterwards to delimit it from its parameters, as with any command.

Unix - if else EOF error

I am writing the following code:
if [ $opt -ge $max -o $opt -le 0 ]
then
echo "Bad";
else
echo "Good";
if [ $opt = "\" -o $opt = "/" ]
then
echo "Good";
else
echo "Invlaid"; //Line number 21
fi
fi //Line number 23 no Line number 24.
this shows an error:
./file.sh: line 21: unexpected EOF while looking for matching `"'
./file.sh: line 24: syntax error: unexpected end of file
If I place this code:
if [ $opt -ge $max -o $opt -le 0 ]
then
echo "Bad";
else
echo "Good";
fi //Line number 23 no Line number 24.
Then there is no error. I am not able to figure out the problem.
Where you write "\" you start a string literal whose first character is a double quote. To include a back slash in a string you have to precede it with another:
"\\"
Backslash \ inside double quotes needs to be escaped or else you can use single quotes like this:
if [ $opt = '\' -o $opt = '/' ]; then
echo "Good"
fi
Single quotes treat the wrapped string literally that's the precise reason single quote in shell cannot be escaped.
opt="\\"
echo $opt
\
if [ $opt = "/" -o $opt = "\\" ]; then echo "Hi"; else echo "bye"; fi
Hi

How to if/else statement in shell script

I'm receiveing an error on a simple script when using if/else statement.
The code:
#!/bin/sh
count=100
if [$count > 3]; then
echo "Test IF"
fi
The error: /bin/ash: line 6: [100: not found
#!/bin/sh
count=100;
if [ "$count" -gt 3 ]; then
echo "Test IF";
fi
Correct your syntax: spaces must be used around [ and ], parameter expansions must be quoted, and -gt is appropriate for numeric comparisons inside of [ ]. > in sh is used as redirection operator; if you want to use it in arithmetical comparison, you must use the bash-only syntax
$(( $count > 3 ))
#!/bin/sh
if [ $var -eq 12 ]; then
echo "This is a numeric comparison if example"
fi
if [ "$var" = "12" ]; then
echo "This is a string if comparison example"
fi
if [[ "$var" = *12* ]]; then
echo "This is a string regular expression if comparison example"
fi
The if statement in shell uses the command [.
Since [ is a command (you could also use 'test'), it requires a space before writing the condition to test.
To see the list of conditions, type:
man test
You'll see in the man page that:
s1 > s2 tests if string s1 is after string s2
n1 gt n2 tests if integer n1 is greater than n2
In your case, using > would work, because string 100 comes after string 3, but it is more logical to write
if [ $count -gt 3 ]; then
echo "test if"
fi
this will also do!
#!/bin/sh
count=100
if [ $count -gt 3 ];
then
echo "Test IF"
fi
if [[ "$x" == "true" ]]; then
echo "value matched"
else
echo "value doesn't matched"
fi

Resources