Converting string to floating point number without bc in bash shell script - bash

I'm getting load average in a bash shell script like so
load=`echo $(cat /proc/loadavg | awk '{print $1}')`
I know piping to bc
load=`echo $(cat /proc/loadavg | awk '{print $1}') \> 3 | bc -l`
is used in almost all examples of how to cast $load as an int but this box does not have bc installed and I am not allowed to add it.
I tried
int=`perl -E "say $load - 0"`
I tried
int=${load%.*}
I tried
int=`printf -v int %.0f "$load"`
What I want to be able to do is
if [ "$int" -gt 3.5 ]; then
How do I get that to evaluate as intended?

You can use awk to produce a success/failure depending on the condition:
# exit 0 (success) when load average greater than 3.5, so take the branch
if awk '{ exit !($1 > 3.5) }' /proc/loadavg; then
# load average was greater than 3.5
fi
Unfortunately, since "success" is 0 in the shell, you have to invert the logic of the condition to make awk exit with the required status. Obviously, you can do this in a number of ways, such as changing > to <=.

You don't need any external tools (like awk) to read this stuff. Load average from /proc/loadavg is always formatted with two decimal places, so you can do this:
read load _ < /proc/loadavg
if [ ${load/./} -gt 350 ]; then
# do something
fi

Related

How to display number to two decimal places, even zero .00 using BC or DC [duplicate]

Greetings!
I uses bс to make some calculations in my script. For example:
bc
scale=6
1/2
.500000
For further usage in my script I need "0.500000" insted of ".500000".
Could you help me please to configure bc output number format for my case?
In one line:
printf "%0.6f\n" $(bc -q <<< scale=6\;1/2)
Just do all your calculations and output in awk:
float_scale=6
result=$(awk -v scale=$floatscale 'BEGIN { printf "%.*f\n", scale, 1/2 }')
As an alternative, if you'd prefer to use bc and not use AWK alone or with 'bc', Bash's printf supports floating point numbers even though the rest of Bash doesn't.
result=$(echo "scale=$float_scale; $*" | bc -q 2>/dev/null)
result=$(printf '%*.*f' 0 "$float_scale" "$result")
The second line above could instead be:
printf -v $result '%*.*f' 0 "$float_scale" "$result"
Which works kind of like sprintf would and doesn't create a subshell.
Quick and dirty, since scale only applies to the decimal digits and bc does not seem to have a sprintf-like function:
$ bc
scale = 6
result = 1 / 2
if (0 <= result && result < 1) {
print "0"
}
print result;
echo "scale=3;12/7" | bc -q | sed 's/^\\./0./;s/0*$//;s/\\.$//'
I believe here is modified version of the function:
float_scale=6
function float_eval()
{
local stat=0
local result=0.0
if [[ $# -gt 0 ]]; then
result=$(echo "scale=$float_scale; $*" | bc -q | awk '{printf "%f\n", $0}' 2>/dev/null)
stat=$?
if [[ $stat -eq 0 && -z "$result" ]]; then stat=1; fi
fi
echo $result
return $stat
}
Can you put the bc usage into a little better context? What are you using the results of bc for?
Given the following in a file called some_math.bc
scale=6
output=1/2
print output
on the command line I can do the following to add a zero:
$ bc -q some_math.bc | awk '{printf "%08f\n", $0}'
0.500000
If I only needed the output string to have a zero for formatting purposes, I'd use awk.

get memory from ps and compare via bash with my limit

I have code that I use in openwrt. I need to check memory which use application
#!/bin/bash
VAR=$(ps | grep sca | grep start | awk '{print $3}')
VAG=$(cat /proc/pid/status | grep -e ^VmSize | awk '{print $2}')
if [ $VAG>28000 ]
then
echo test
fi
No matter if I use VAR or VEG(for example VAR/VAG equal 15000), I can get work this code. I always get "test"
Your if statement is incorrect. The test command (aka [) must receive separate arguments for the operands and the operator. Also, > is for string comparisons; you need to use -gt instead.
if [ "$VAG" -gt 28000 ]
Since you are using bash, you can use the more readable arithmetic command instead of [:
if (( VAG > 28000 ))

integer expression expected [bash does not understand .]

I made a small script to kill PID's if they exceed expected cpu usage. It works, but there is a small problem.
Script:
while [ 1 ];
do
cpuUse=$(ps -eo %cpu | sort -nr | head -1)
cpuMax=80
PID=$(ps -eo %cpu,pid | sort -nr | head -1 | cut -c 6-20)
if [ $cpuUse -gt $cpuMax ] ; then
kill -9 "$PID"
echo Killed PID $PID at the usage of $cpuUse out of $cpuMax
fi
exit 0
sleep 1;
done
It works if the integer is three digits long but fails if it drops to two and displays this:
./kill.sh: line 7: [: 51.3: integer expression expected
My question here is, how do I make bash understand the divider so it can kill processes under three digits.
You are probably getting leading space in that variable. Try piping with tr to strip all spaces first:
cpuUse=$(ps -eo %cpu | sort -nr | head -1 | tr -d '[[:space:]]')
Remove text after dot from cpuUse variable:
cpuUse="${cpuUse%%.*}"
Also better to use quotes in if condition:
if [ "$cpuUse" -gt "$cpuMax" ] ; then
OR better use arithmetic operator (( and )):
if (( cpuUse > cpuMax )); then
As you see, bash doesn't grok non-integer numbers. You need to eliminate the decimal point and the following digits from $cpuUse before doing the comparison":
cpuUse=$(sed 's/\..*/' <<<$cpuUse)
However, this is really a job for awk. It will simplify much of what you're doing. Whenever you find yourself with greps of greps, or head and then cuts, you should be dealing with awk. Awk can easily combine these multiple piped seds, greps, cuts, heads, into a single command.
By the way, the correct ps command is:
$ ps -eocpu="",pid=""
Using the ="" will eliminate the heading and simply give you the CPU and PID.
Looking at your program, there's no real need to sort. You're simply looking for all processes above that $cpuMax threshold:
ps -eo %cpu="",pid="" | awk '$1 > 80 {print $2}'
That prints out your PIDs which are over your threshold. Awk automatically loop through your entire input line-by-line. Awk also automatically divides each line into columns, and assigns each a variable from $1 and up. You can change the field divider with the -F parameter.
The above awk says look for all lines where the first column is above 80%, (the CPU usage) and print out the second column (the pid).
If you want some flexibility and be able to pass in different $cpuMax, you can use the -v parameter to set Awk variables:
ps -eo %cpu="",pid="" | awk -vcpuMax=$cpuMax '$1 > cpuMax {print $2}'
Now that you can pipe the output of this command into a while to delete all those processes:
pid=$(ps -eo %cpu="",pid="" | awk -vcpuMax=$cpuMax '$1 > cpuMax {print $2}')
if [[ -n $pid ]]
then
kill -9 $pid
echo "Killed the following processes:" $pid
fi

Error in Echo of awk command piped to wc -l

I have hundreds of files containing lines similar to this:
>34764998 Halalkalicoccus_jeotgali_B3 -132.6938 Halalkalicoccus 0.528 Halobacteriaceae 0.638 Halobacteriales 0.648 Halobacteria 0.706 Euryarchaeota 0.850
I am interested in counting the number of items in column 5 that is less than 0.1, ...0.95. I have written a bash script that calls an AWK command to look evaluate the column value then pipe it into wc -l (see below). However, I don't quite have my $, ', and brackets arranged correctly. Can anyone advise me as to what I did incorrectly? This is probably not the most efficient way so I welcome suggestions, but I do want to know what I did wrong with the code I listed.
for fileName in 4440319.3_genus.txt 4440372.3_genus.txt 4440373.3_genus.txt 4440378.3_genus.txt 4440379.3_genus.txt 4440380.3_genus.txt 4440381.3_genus.txt
do
echo $fileName
for number in 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 0.95
do
#NUM={awk '$5 < '$number' {print $5}' $filename | wc -l}
NUM={awk '$5 < $number {print $5}' $filename | wc -l}
#NUM=${awk '$5 < '$number' {print $5}' $filename | wc -l}
#NUM=${awk '$5 < $number {print $5}' $filename | wc -l}
echo $NUM
done
done
exit 0
All variations yield invalid option errors depending on which line is un-commented.
Thank you very much.
you don't need the wc -l pipe, even don't need the for loop of filename, try this:
awk -v n=0.95 '$5<n{a++}END{print a}' *_genus.txt
Assuming that you're using sh or bash, here's what I'd do:
NUM=`awk -v x=$number '$5 < x {print $5}' $fileName | wc -l`
Some explanation why this works and your attempts do not work:
You need to execute the pipe and store its output in variable NUM. That's why you need the backquotes around the pipe.
Your $number is a shell variable. Shell variable expansion does not take place inside single quotes, so your $number in the awk script has no chance of being substituted with the numbers that you want. To deal with this, you can either use double quotes to embed the number in the right place (this will cause some trouble because of the other dollar signs in the awk script that you don't want to be shell expanded), or you can use an awk variable that is externally initialized. That's what the -v argument does.
Last but not least, you need to fix the lowercase 'N' in filename.
Here I give the full script:
for fileName in 4440319.3_genus.txt 4440372.3_genus.txt 4440373.3_genus.txt 4440378.3_genus.txt 4440379.3_genus.txt 4440380.3_genus.txt 4440381.3_genus.txt
do
echo $fileName
for number in 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 0.95
do
NUM={awk -v n=$number '$5<n{a++}END{print a}'}
echo "$NUM records is less than $number"
done
done
exit 0

Bash script: specify bc output number format

Greetings!
I uses bс to make some calculations in my script. For example:
bc
scale=6
1/2
.500000
For further usage in my script I need "0.500000" insted of ".500000".
Could you help me please to configure bc output number format for my case?
In one line:
printf "%0.6f\n" $(bc -q <<< scale=6\;1/2)
Just do all your calculations and output in awk:
float_scale=6
result=$(awk -v scale=$floatscale 'BEGIN { printf "%.*f\n", scale, 1/2 }')
As an alternative, if you'd prefer to use bc and not use AWK alone or with 'bc', Bash's printf supports floating point numbers even though the rest of Bash doesn't.
result=$(echo "scale=$float_scale; $*" | bc -q 2>/dev/null)
result=$(printf '%*.*f' 0 "$float_scale" "$result")
The second line above could instead be:
printf -v $result '%*.*f' 0 "$float_scale" "$result"
Which works kind of like sprintf would and doesn't create a subshell.
Quick and dirty, since scale only applies to the decimal digits and bc does not seem to have a sprintf-like function:
$ bc
scale = 6
result = 1 / 2
if (0 <= result && result < 1) {
print "0"
}
print result;
echo "scale=3;12/7" | bc -q | sed 's/^\\./0./;s/0*$//;s/\\.$//'
I believe here is modified version of the function:
float_scale=6
function float_eval()
{
local stat=0
local result=0.0
if [[ $# -gt 0 ]]; then
result=$(echo "scale=$float_scale; $*" | bc -q | awk '{printf "%f\n", $0}' 2>/dev/null)
stat=$?
if [[ $stat -eq 0 && -z "$result" ]]; then stat=1; fi
fi
echo $result
return $stat
}
Can you put the bc usage into a little better context? What are you using the results of bc for?
Given the following in a file called some_math.bc
scale=6
output=1/2
print output
on the command line I can do the following to add a zero:
$ bc -q some_math.bc | awk '{printf "%08f\n", $0}'
0.500000
If I only needed the output string to have a zero for formatting purposes, I'd use awk.

Resources