Linux Bash - Comparing two variables in an if statement - linux

I am trying to perform a variable swap where the user enters 2 different numbers and a check is performed to make sure that the second number "end" is bigger then the first number "start". If the starting number is bigger then the end number it will perform a swap so that the later calculations will work.
The error that I am getting is:
./Boot.sh: line 94: [: -ne: unary operator expected
if [ $end -gt $start ]
then
start=$swapper
end=$start
swapper=$end
fi
This is the full code as I seem to have made a few mistakes by the comments, I have just tried double brackets and am still having the same error.
{
counter=0
while :
do
if [ $counter -gt '0' ]
then
printf "\nWould you like to continue terminating processes?\n"
echo "Type 1 to contiue or 0 to exit"
read endProgram
if [ $endProgram -ne '1' ]
then
break
fi
fi
echo "Welcome to Max process killer"
while :
do
echo "Enter the first number of the process range"
read start
echo "Enter the last number of the process range"
read end
if [ $start -le '3' -o $end -le '3' ]
then
echo "Your first and last pid IDs must be geater then 3"
read -n 1
break
if [[ $end -gt $start ]]
then
start=$swapper
end=$start
swapper=$end
fi
fi
printf "\nAre you sure you would like to terminate these processes?\n"
echo "Enter 1 to confirm or 0 to cancel"
read confirm
if [ $read -ne '1' ]
then
break
fi
while [ $start -le $end ]
do
kill -9 "$start"
echo "Process ID:"$start "has been terminated"
start=$(( $start + 1 ))
done
break
done
counter=$(($counter + 1))
done
}

Your code:
read confirm
if [ $read -ne '1' ]
You read input to variable confirm and not to variable read. Variable read is empty and you get the error:
./Boot.sh: line 94: [: -ne: unary operator expected
Hint: Use a default value (e.g. 0) to avoid an empty variable:
if [ "${confirm:-0}" -ne '1' ]
From man bash:
${parameter:-word}: Use Default Values. If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.
${parameter:=word}: Assign Default Values. If parameter is unset or null, the expansion of word is assigned to parameter. The value of parameter is then substituted. Positional parameters and special parameters may not be assigned to in this way.

Try using double brackets. They are generally safer. Here's a good wiki page comparing [[]] to [].
if [[ $end -gt $start ]]
then
swapper=$start
start=$end
end=$swapper
fi

Related

Read string and convert to INT (BASH)

I have a simple script in Bash to read a number in a file and then compare it with a different threshold. The output is this:
: integer expression expected
: integer expression expected
OK: 3
My code is this:
#!/bin/bash
wget=$(wget http://10.228.28.8/ -O /tmp/wget.txt 2>/dev/null)
output=$(cat /tmp/wget.txt | awk 'NR==6')
#output=7
echo $output
if [ $output -ge 11 ];then
echo "CRITICAL: $output"
exit 2
elif [ $output -ge 6 ] && [ $output -lt 11 ];then
echo "WARNING: $output"
exit 1
else
echo "OK: $output"
exit 0
fi
rm /tmp/wget.txt
I know what is the problem, I know that I'm reading a string and I try to compare a int. But I don't know how can I do to read this file and convert the number to read in a int var..
Any ideas?
The problem occurs when $output is the empty string; whether or not you quote the expansion (and you should), you'll get the integer expression required error. You need to handle the empty string explictly, with a default value of zero (or whatever default makes sense).
wget=$(wget http://10.228.28.8/ -O /tmp/wget.txt 2>/dev/null)
output=$(awk 'NR==6' < /tmp/get.txt)
output=${output:-0}
if [ "$output" -ge 11 ];then
echo "CRITICAL: $output"
exit 2
elif [ "$output" -ge 6 ];then
echo "WARNING: $output"
exit 1
else
echo "OK: $output"
exit 0
fi
(If you reach the elif, you already know the value of $output is less than 11; there's no need to check again.)
The problem also occurs, and is consistent with the error message, if output ends with a carriage return. You can remove that with
output=${output%$'\r'}
There are a couple of suggestions from my side regarding your code.
You could explicitly tell bash the output is an integer
declare -i output # See [1]
Change
output=$(cat /tmp/wget.txt | awk 'NR==6') # See [2]
may be better written as
output=$(awk 'NR==6' /tmp/wget.txt )
Change
if [ $output -ge 11 ]
to
if [ "0$output" -ge 11 ] # See [4]
or
if (( output >= 11 )) # Better See [3]
References
Check bash [ declare ].
Useless use of cat. Check [ this ]
Quoting [ this ] answer :
((...)) enable you to omit the dollar signs on integer and array variables and include spaces around operators for readability. Also empty variable automatically defaults to 0 in such a statement.
The zero in the beginning of "0$output" help you deal with empty $output
Interesting
Useless use of cat is a phrase that has been resounding in SO for long. Check [ this ]
[ #chepner ] has dealt with the empty output fiasco using [ bash parameter expansion ] in his [ answer ], worth having a look at.
A simplified script:
#!/bin/bash
wget=$(wget http://10.228.28.8/ -O /tmp/wget.txt 2>/dev/null)
output=$(awk 'NR==6' </tmp/wget.txt )
output="$(( 10#${output//[^0-9]} + 0 ))"
(( output >= 11 )) && { echo "CRITICAL: $output"; exit 2; }
(( output >= 6 )) && { echo "WARNING: $output"; exit 1; }
echo "OK: $output"
The key line to cleanup any input is:
output="$(( 10#${output//[^0-9]} + 0 ))"
${output//[^0-9]} Will leave only digits from 0 to 9 (will remove all non-numeric chars).
10#${output//[^0-9]} Will convert output to a base 10 number.
That will correctly convert numbers like 0019
"$(( 10#${output//[^0-9]} + 0 ))" Will produce a zero for a missing value.
Then the resulting number stored in output will be compared to limits and the corresponding output will be printed.
In BASH, It is a good idea to use double brackets for strings:
if [[ testing strings ]]; then
<whatever>
else
<whatever>
fi
Or double parenthesis for integers:
if (( testing ints )); then
<whatever>
else
<whatever>
fi
For example try this:
var1="foo bar"
if [ $var1 == 'foo bar' ]; then
echo "ok"
fi
Result:
$ bash: [: too many arguments
Now, this:
var2="foo bar"
if [[ $a == "foo bar" ]]; then
echo "ok"
fi
Result:
ok
For that, your code in BASH:
if [[ $output -ge 11 ]]; then
echo "CRITICAL: $output"
exit 2
elif [[ $output -ge 6 ]]; then
echo "WARNING: $output"
exit 1
else
echo "OK: $output"
exit 0
fi

Script with parameter

I supossed to make a script that given an number it count to 0, I managed to do this and it's working:
#!/bin/bash
echo -n "type a number: "
read number; echo
while [ $number -ge 0 ]; do
echo -n "$number"
number=$((number-1))
done
echo
Well, I changed it because I need to pass the number by an parameter ex: "./script 5" and it must show the countdown till 0, but its getting in looping. I kind new on all it script/stack what Im doing wrong?
#!/bin/bash
if [ "$*" = "" ]; then
echo
echo "not correct"
echo "must be a int number"
echo
exit
fi
while [ "$1" -ge 0 ]; do
echo "$1"
cont='expr $1-1'
done
echo
You're always using [ "$1" -ge 0 ] as your condition, but the value you actually modify/update is cont, not $1. (Moreover, you modify it based on the value of $1, which isn't changing, so you only ever set $cont to one less than the original value of $1).
Consider:
#!/bin/bash
[[ $1 ]] || { printf '%s\n' "First argument must be an integer" >&2; exit 1; }
for ((i=$1; i>=0; i--)); do
echo "$i"
done
...and note, among the various changes:
We're consistently referring to the first argument passed as $1, rather than also sometimes referring to it as $*
When we select a variable to modify ($i, here, rather than $cont), we use that same variable in our tests, and also as the source for modification in the loop.
Using expr for math is antiquated; POSIX sh allows $(( )) to create a math context, and bash extends this to also allow C-style for loops in a math context.

Why this command not found when i'm comparing strings in an array?

My sample code is here
#!/bin/bash
file="output2.txt"
numbers="$(cut -d',' -f2 output2.txt)"
lines="$(cut -f2 output2.txt)"
hours="$(cut -d',' -f1 output2.txt)"
array_numbers=( $numbers )
lines_array=( $lines )
hours_array=( $hours )
difference=$1
let range=$1-1000
for (( i = 0 ; i < ${#array_numbers[#]} ; i++ ))
do
let num=$(( 10#${array_numbers[$i+1]} - 10#${array_numbers[$i]} ))
if [ $num -gt $1 ]
then
echo ${lines_array[$i+1]} "and" ${lines_array[$i]} "has a difference more than $1"
elif [ $num -ge 0 ] && [ $num -lt $range ]
then
echo ${lines_array[$i+1]} "and" ${lines_array[$i]} "has a difference more than $1"
elif [ $num -le $1 ]
then
if [${hours_array[$i+1]} != ${hours_array[$i]}]
then
echo ${lines_array[$i+1]} "and" ${lines_array[$i]} "has a difference more than one second"
fi
fi
done
I'm working with the same output2.txt again:
12:43:40,317
12:43:40,318
12:43:40,332
12:43:40,333
12:43:40,334
12:43:40,335
12:43:40,336
12:43:40,337
12:43:40,338
12:43:40,339
12:43:40,353
12:43:40,354
12:43:40,356
12:43:40,358
12:43:40,360
12:43:40,361
12:43:40,362
12:43:40,363
12:43:40,364
12:43:40,365
12:43:40,382
12:43:40,384
12:43:40,385
12:43:40,387
12:43:40,388
12:43:40,389
12:43:40,390
12:43:40,391
12:43:40,404
12:43:40,405
12:43:40,406
12:43:40,407
12:43:40,408
12:43:40,409
12:43:40,410
12:43:40,412
12:43:40,413
12:43:40,414
12:43:40,415
12:43:40,428
12:43:40,429
12:43:40,431
12:43:40,432
12:43:40,433
12:43:40,434
12:43:40,435
12:43:40,436
12:43:40,437
12:43:40,438
12:43:40,440
12:43:40,443
12:43:40,458
12:43:40,459
12:43:40,460
12:43:40,461
12:43:40,462
12:43:40,463
12:43:40,464
12:43:40,465
12:43:40,466
12:43:40,479
12:43:40,480
12:43:40,481
12:43:40,482
12:43:40,483
12:43:40,484
12:43:40,485
12:43:40,486
12:43:40,487
12:43:40,501
12:43:40,503
12:43:40,504
12:43:40,505
12:43:40,506
12:43:40,509
12:43:40,510
12:43:40,511
12:43:40,512
12:43:40,513
12:43:40,514
12:43:40,515
12:43:40,517
12:44:40,518
What I want to do is take the difference as parameter and if there is a value difference more than 100 miliseconds than I'm wanna print output. The parts
for (( i = 0 ; i < ${#array_numbers[#]} ; i++ ))
do
let num=$(( 10#${array_numbers[$i+1]} - 10#${array_numbers[$i]} ))
if [ $num -gt $1 ]
then
echo ${lines_array[$i+1]} "and" ${lines_array[$i]} "has a difference more than $1"
elif [ $num -ge 0 ] && [ $num -lt $range ]
then
echo ${lines_array[$i+1]} "and" ${lines_array[$i]} "has a difference more than $1"
are actually working well , but i realized that if input has such a columns in order like the last part
12:43:40,517
12:44:40,518
it won't print anything so i put the last elif statement to my code but even it prints hours_array good, it doesn't work with while i'm comparing them. The output is always :
script.sh: line 22: [12:43:00: command not found
Why doesn't it accept this compare or is the problem is about my bash version ?
Thank you in advance for your help.
Add space before and after [. It is an 'alias' to the test buitin command.
You should also add double quote " around your variable. Because if they are empty, bash won't recognize them as a empty word.
And I generally use double brackets [[ for test condition which is more safer and has more features.
Example:
if [[ "${hours_array[$i+1]}" != "${hours_array[$i]}" ]]
You need a space here (the [ is a command)
if [ ${hours_array[$i+1]} != ${hours_array[$i]} ]
Missing space after [. [ is a command, so it needs to be separated from its arguments.
if [ ${hours_array[$i+1]} != ${hours_array[$i]} ]
I find few things that can be changed in this code.
Add space after [ and before ].
Add double quotes so that in case if variable is empty, script does not throw error.
if [ "${hours_array[$i+1]}" != "${hours_array[$i]}" ]
Also when you reach the last line, $i + 1 will fail. Hence, following would be better.
for (( i = 0 ; i < ${#array_numbers[#]} - 1 ; i++ ))

Why does [$value -lt 10] in shell result in command not found? [duplicate]

This question already has answers here:
"Command not found" when attempting integer equality in bash
(3 answers)
Closed 8 years ago.
Output 1:
Enter your value: 12
./testscript.sh: line 4: 12: command not found
Your value is more than 10
Output 2:
Enter your value: 5
./testscript.sh: line 4: 12: command not found
Your value is more than 10
I need to know what is wrong. My Linux test is just tomorrow:(
#!/bin/bash
echo -n "Enter your value: "
read value
if [$value -lt 10]
then
echo "Your value is less than 10"
else
echo "Your value is more than 10"
fi
your if statement should be as below. A space before ']' and space after '['
if [ $value -lt 10 ]
EDIT
As per the comments
you can always add optional ; at the end of the line. The below script would work fine.
a=20;
if [ $a -gt 10 ];
then
echo "true";
else
echo "false";
fi
you need to put your condition in the [ condition ]. The below one does not work.
( condition )
It would say command not found. As '(' is not command. where as '[' is a command in order to check a condition
And the more appropriate way is to use [[ ]] over [ ] when in Bash since you can avoid word splitting and pathname expansion with it. Other conditions can be added as well:
if [[ ! $value =~ [0-9]+ ]]; then
echo "Invalid input."
elif [[ value -lt 10 ]]; then
echo "Your value is less than 10."
elif [[ value -eq 10 ]]; then
echo "Your value is 10."
else
echo "Your value is more than 10."
fi
To throw yet another option into the mix: bash has (( ... )) -- arithmetic conditions:
if (( $value < 10 )); then ...
http://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs
One thing you can do in bash with arithmetic expressions is to drop the $.
if (( value < 10 )); then
This is documented a bit obscurely in Shell arithmetic: "Within an expression, shell variables may also be referenced by name without using the parameter expansion syntax."
This may appeal to aficionados of C-like languages, but it's a bit out of step with the rest of the languages, and it doesn't apply to all variables (such as special paramaters ($#)
and array elements (${foo[3]})).

Syntax error near unepected token do

This is my code for a bubble sort on n numbers:
#!/bin/bash
echo -n "Input n, the number of numbers"
read N
declare -a array[N]
echo -e "Input the elements, press enter after each element"
for i in seq 1 $N
do
read array[$i]
done
swap1()
{ # for swapping two numbers, we are employing bubble sort
local temp = ${array[$1]}
array[$1] = ${array[$2]}
array[$2]=$temp
return
}
numb_elements=${#array[#]}
let "comparisons = $numb_elements - 1"
count=1
while [ "$comparisons" -gt 0]
do
index =0
while[ "$index" -lt "$comparisons" ];do
if [ ${array[$index]} \> ${array[ 'expr $index + 1']} ]
then
swap1 $index 'expr $index + 1'
fi
let "index += 1" # Or, index+=1 on Bash, ver. 2.1 or newer
done
let "comparisons -=1"
echo
echo "$count: ${array[#]}
echo
let "count +=1"
done
exit 0
I have two problems with this code:
the input array just takes 3 numbers
and then i get an error on line 42 saying syntax error for the command while do
I have tried while [] ; do, but it doesn't work.
Its just been a day that i have been trying bash syntax.
Moreover do not write
for i in seq 1 $N
which iterate i over the set {"seq","1",$N}, but type
for i in $(seq 1 $N)
to insert the result of the command as part of code.
You forgot the closing quote in this line :
echo "$count: ${array[#]}
Also the code of the nested loops is badly indented, so it is a bit hard to read and debug.
So far I have found the following errors:
while [ "$comparisons" -gt 0 ]
^ missing space here
while [ "$index" -lt "$comparisons" ];do
^ missing space
echo "$count: ${array[#]}"
^ missing quote
Note that in bash [ is equivalent to test command, so a space is required around [ and ] unlike many other programming languages.
You made a series of errors:
correct spaces are fundamental to shell scripting
missing `` apices to execute code and get the output
logic error (starting inserting from the second array element and using it from the first one)
iterating the wrong number of time for the bubblesort alg
This is your code corrected.
#!/bin/bash
swap1() { # for swapping two numbers, we are employing bubble sort
local temp=${array[$1]}
array[$1]=${array[$2]}
array[$2]=$temp
return
}
echo -n "Input n, the number of numbers: "
read N
declare -a array[$N]
echo -e "Input the elements, press enter after each element"
for i in `seq 1 $N`
do
read array[$i]
done
numb_elements=${#array[#]}
#let "comparisons = $numb_elements - 1"
comparisons=$numb_elements
count=1
while [ "$comparisons" -gt 0 ]
do
index=1
while [ "$index" -lt "$comparisons" ]
do
tmp=`expr $index + 1`
if [ ${array[$index]} -gt ${array[$tmp]} ]
then
swap1 $index $tmp
fi
let "index += 1" # Or, index+=1 on Bash, ver. 2.1 or newer
done
let "comparisons -= 1"
echo
echo "$count: ${array[#]}"
echo
let "count += 1"
done
exit 0
Try this:
while [ "$comparisons" -gt 0]
should be (notice space before the closing bracket ]):
while [ "$comparisons" -gt 0 ]

Resources