Comparison between array items - bash

I've written a script to calculate the bandwidth usage of an OpenVZ container over time and suspend it if it uses too much too quickly. Here is the script so far:
#!/bin/bash
# Thresholds are in bytes per second
LOGDIR="/var/log/outbound_ddos"
THRESHOLD1=65536
THRESHOLD2=117964
while [ 1 ]
do
for veid in $(/usr/sbin/vzlist -o veid -H)
do
# Create the log file if it doesn't already exist
if ! test -e $LOGDIR/$veid.log; then
touch $LOGDIR/$veid.log
fi
# Parse out the inbound/outbound traffic and assign them to the corresponding variables
eval $(/usr/sbin/vzctl exec $veid "grep venet0 /proc/net/dev" | \
awk -F: '{print $2}' | awk '{printf"CTOUT=%s\n", $9}')
# Print the output and a timestamp to a log file
echo $(date +%s) $CTOUT >> $LOGDIR/$veid.log
# Read last 10 entries into arrays
i=0
tail $LOGDIR/$veid.log | while read time byte
do
times[i]=$time
bytes[i]=$byte
let ++i
done
# Time checks & calculations for higher threshold
counter=0
for (( i=0; i<9; i++ ))
do
# If we have roughly the right timestamp
if (( times[9-i] < times[8-i] + 20 ))
then
# If the user has gone over the threshold
if (( bytes[9-i] > bytes[8-i] + THRESHOLD2 * 10 ))
then let ++counter
fi
fi
done
# Now check counter
if (( counter == 9 ))
then vzctl stop $veid
fi
# Same for lower threshold
counter=0
for (( i=0; i<3; i++ ))
do
# If we have roughly the right timestamp
if (( times[3-i] < times[2-i] + 20 ))
then
# If the user has gone over the threshold
if (( bytes[3-i] > bytes[2-i] + THRESHOLD1 * 10 ))
then let ++counter
fi
fi
done
# Now check counter
if (( counter == 2 ))
then vzctl stop $veid
fi
done
sleep 10
done
I've checked the numbers in /var/log/outbound_ddos/vm101.log and they're increasing by more than the threshold, but nothing is happening.
I added some echo statements to try and figure out where the problem is and it seems to be this comparison that's returning false:
if (( bytes[9-i] > bytes[8-i] + THRESHOLD2 * 10 ))
So then I tried the following, which printed out nothing:
echo ${bytes[9-i]}
Could anyone point me in the right direction? I think the script is nearly done, probably something very simple.

Your shell runs the while read loop in a subshell (see here for why it does not work as expected), so your array magic does not propagate outside the tail | while construct.
Read this and fix accordingly :-)

Related

How do I create large CSVs in seconds?

I am trying to create 1000s of large CSVs rapidly. This function generates the CSVs:
function csvGenerator () {
for ((i=1; i<=$NUMCSVS; i++)); do
CSVNAME=$DIRNAME"-"$CSVPREFIX$i$CSVEXT
HEADERARRAY=()
if [[ ! -e $CSVNAME ]]; then #Only create csv file if it not exist
touch $CSVNAME
echo "file: "$CSVNAME "created at $(date)" >> ../status.txt
fi
for ((j=1; j<=$NUMCOLS; j++)); do
if (( j < $NUMCOLS )) ; then
HEADERNAME=$DIRNAME"-csv-"$i"-header-"$j", "
elif (( j == $NUMCOLS )) ; then
HEADERNAME=$DIRNAME"-csv-"$i"-header-"$j
fi
HEADERARRAY+=$HEADERNAME
done
echo $HEADERARRAY > $CSVNAME
for ((k=1; k<=$NUMROWS; k++)); do
ROWARRAY=()
for ((l=1; l<=$NUMCOLS; l++)); do
if (( l < $NUMCOLS )) ; then
ROWVALUE=$DIRNAME"-csv-"$i"-r"$k"c"$l", "
elif (( l == $NUMCOLS )) ; then
ROWVALUE=$DIRNAME"-csv-"$i"-r"$k"c"$l
fi
ROWARRAY+=$ROWVALUE
done
echo $ROWARRAY >> $CSVNAME
done
done
}
The script takes ~3 mins to generate a CSV with 100k rows and 70 cols. What do I need to do to generate these CSVs at the rate of 1 CSV/~10 seconds?
Let me start by saying that bash and "performant" don't usually go together in the same sentence. As other commentators suggested, awk may be a good choice that's adjacent in some senses.
I haven't yet had a chance to run your code, but it opens and closes the output file once per row — in this example, 100,000 times. Each time it must seek to the end of the file so that it can append the latest row.
Try pulling the actual generation (everything after for ((j=1; j<=$NUMCOLS; j++)); do) into a new function, like generateCsvContents. In that new function, don't reference $CSVNAME, and remove the redirections on the echo statements. Then, in the original function, call the new function and redirect its output to the filename. Roughly:
function csvGenerator () {
for ((i=1; i<=NUMCSVS; i++)); do
CSVNAME=$DIRNAME"-"$CSVPREFIX$i$CSVEXT
if [[ ! -e $CSVNAME ]]; then #Only create csv file if it not exist
echo "file: $CSVNAME created at $(date)" >> ../status.txt
fi
# This will create $CSVNAME if it doesn't yet exist
generateCsvContents > "$CSVNAME"
done
}
function generateCsvContents() {
HEADERARRAY=()
for ((j=1; j<=NUMCOLS; j++)); do
if (( j < NUMCOLS )) ; then
HEADERNAME=$DIRNAME"-csv-"$i"-header-"$j", "
elif (( j == NUMCOLS )) ; then
HEADERNAME=$DIRNAME"-csv-"$i"-header-"$j
fi
HEADERARRAY+=$HEADERNAME
done
echo $HEADERARRAY
for ((k=1; k<=NUMROWS; k++)); do
ROWARRAY=()
for ((l=1; l<=NUMCOLS; l++)); do
if (( l < NUMCOLS )) ; then
ROWVALUE=$DIRNAME"-csv-"$i"-r"$k"c"$l", "
elif (( l == NUMCOLS )) ; then
ROWVALUE=$DIRNAME"-csv-"$i"-r"$k"c"$l
fi
ROWARRAY+=$ROWVALUE
done
echo "$ROWARRAY"
done
}
"Not this way" is I think the answer.
There are a few problems here.
You're not using your arrays as arrays. When you treat them like strings, you affect only the first element in the array, which is misleading.
The way you're using >> causes the output file to be opened and closed once for every line. That's potentially wasteful.
You're not quoting your variables. In fact, you're quoting the stuff that doesn't need quoting, and not quoting the stuff that does.
Upper case variable names are not recommended, due to the risk of collision with system variables. ref
Bash isn't good at this. Really.
A cleaned up version of your function might look like this:
csvGenerator2() {
for (( i=1; i<=NUMCSVS; i++ )); do
CSVNAME="$DIRNAME-$CSVPREFIX$i$CSVEXT"
# Only create csv file if it not exist
[[ -e "$CSVNAME" ]] && continue
touch "$CSVNAME"
date "+[%F %T] created: $CSVNAME" | tee -a status.txt >&2
HEADER=""
for (( j=1; j<=NUMCOLS; j++ )); do
printf -v HEADER '%s, %s-csv-%s-header-%s' "$HEADER" "$DIRNAME" "$i" "$j"
done
echo "${HEADER#, }" > "$CSVNAME"
for (( k=1; k<=NUMROWS; k++ )); do
ROW=""
for (( l=1; l<=NUMCOLS; l++ )); do
printf -v ROW '%s, %s-csv-%s-r%sc%s' "$ROW" "$DIRNAME" "$i" "$k" "$l"
done
echo "${ROW#, }"
done >> "$CSVNAME"
done
}
(Note that I haven't switched the variables to lower case because I'm lazy, but it's still a good idea.)
And if you were to make something functionally equivalent in awk:
csvGenerator3() {
awk -v NUMCSVS="$NUMCSVS" -v NUMCOLS="$NUMCOLS" -v NUMROWS="$NUMROWS" -v DIRNAME="$DIRNAME" -v CSVPREFIX="$CSVPREFIX" -v CSVEXT="$CSVEXT" '
BEGIN {
for ( i=1; i<=NUMCSVS; i++) {
out=sprintf("%s-%s%s%s", DIRNAME, CSVPREFIX, i, CSVEXT)
if (!system("test -e " CSVNAME)) continue
system("date '\''+[%F %T] created: " out "'\'' | tee -a status.txt >&2")
comma=""
for ( j=1; j<=NUMCOLS; j++ ) {
printf "%s%s-csv-%s-header-%s", comma, DIRNAME, i, j > out
comma=", "
}
printf "\n" >> out
for ( k=1; k<=NUMROWS; k++ ) {
comma=""
for ( l=1; l<=NUMCOLS; l++ ) {
printf "%s%s-csv-%s-r%sc%s", comma, DIRNAME, i, k, l >> out
comma=", "
}
printf "\n" >> out
}
}
}
'
}
Note that awk does not suffer from the same open/closer overhead mentioned earlier with bash; when a file is used for output or as a pipe, it gets opened once and is left open until it is closed.
Comparing the two really highlights the choice you need to make:
$ time bash -c '. file; NUMCSVS=1 NUMCOLS=10 NUMROWS=100000 DIRNAME=2 CSVPREFIX=x CSVEXT=.csv csvGenerator2'
[2019-03-29 23:57:26] created: 2-x1.csv
real 0m30.260s
user 0m28.012s
sys 0m1.395s
$ time bash -c '. file; NUMCSVS=1 NUMCOLS=10 NUMROWS=100000 DIRNAME=3 CSVPREFIX=x CSVEXT=.csv csvGenerator3'
[2019-03-29 23:58:23] created: 3-x1.csv
real 0m4.994s
user 0m3.297s
sys 0m1.639s
Note that even my optimized bash version is only a little faster than your original code.
Refactoring your two inner for-loops to loops like this will save time:
for ((j=1; j<$NUMCOLS; ++j)); do
HEADERARRAY+=$DIRNAME"-csv-"$i"-header-"$j", "
done
HEADERARRAY+=$DIRNAME"-csv-"$i"-header-"$NUMCOLS

trouble debugging a .bash file that separates and echoes either student or student score

Like the title implies, I'm currently having trouble debugging a .bash file. As you can tell, I'm still very new to bash and unix in general. Inside The inputfile that hw3.bash executes on contains the following strings in two columns:
jack 80
mary 95
michael 60
jeffrey 90
The file will print out the names only, then scores only, then highest score, then lowest, then rank, etc.
Both lines 72 and 150 are the hiccups in the program that i cannot seem to debug. Is this a indentation issue or simply a grammatical issue.
line 72: unexpected EOF while looking for matching `''
line 150: syntax error: unexpected end of file
#1.The first positional argument ($1) provides the file name. Assign it to a
# variable named inputfile.
inputfile=$1
#2.Test if the variable inputfile refers to a file. If not, print out a proper
# message and exit with an exit code of 1.
if [[ -e inputfile ]]; then
echo "inputfile is not a file'
exit 1
fi
#3.Suppose each line of the input file is made up of the first name of a
#student followed by a score (the first name and score are separate by a
# space). Put the first names in the input file into an array called names.
record=( $(cat $inputfile | awk 'END{print NR}' ))
names=( $(cat $inputfile | awk'{print $1}'))
echo ${names[*]}
#4.Using a similar approach, put the corresponding scores into an
# array called scores.
scores=( $(cat $inputfile | awk'{print $2}'))
echo ${scores[*]}
#5.Print names and corresponding scores (i.e. output should look the same as
# the input file). You must use a loop to do this.
names=( $(cat $inputfile | awk'{print $1}'))
echo${names[*]}
scores=( $(cat $inputfile | awk'{print $2}'))
echo${names[*]}
for((i=0;i<${names[*] && $i<scores[*];i++))
do
echo{$names[i]} {$scores[*]}
done
#6.Find the highest scorer, and print the name and the score. You may assume
#that there is only one highest score.
maxVal=1
maxIndex=1
for(( i=0; i<$#names[*]} && i<${#scores[*]}; i++ ))
do
if [[ (-n ${scores[$i]}) ]]
then
if(( ${scores[$i]} > $maxValue ))
then
maxVal=${scores[$i]}
maxIndex=$i
fi
fi
done
echo "Highest Scorer:" ${names[$maxIndex]} " " $maxVal
#7.Find the lowest scorer, and print the name and the score. You may assume
#that there is only one lowest score.
minVal=10000
maxIndex=1
for(( i=0; i<${#names[*]} && i<${#scores[*]}; i++ ))
do
if [[ (-n ${scores[$i]}) ]]
then
if(( $minVal > ${scores[i]} ))
then
minVal=${scores[$i]}
minIndex=$i;
fi
done
echo "Lower Scorer:' ${names[$minIndex]} " " $minVal
#8.Calculate the average of all scores, and print it.
avg=0
total=0;
for(( i=0;i<${#names[*]} && i<${$#scores[*]};i++ ))
do
if [[ (-n ${scores[$i]} ]]
then
total=$(( $total + ${scores[$i]} ))
fi
#9.Sort the arrays in terms of scores (in descending order). The final
#position of each name in the array names must match with the position of the
# corresponding score in the array scores.
m=${names[*]}
n=${scores[*]}
for(( i=0; i<$n && i<$m; i++ ))
do
maxValue=1
maxIndex=0
for(( i=0; j<$n && j<$m; j++))
do
if [[ !(-z ${scores[$j]} ) ]]
then
if (( $maxVal < ${scores[$j]} ))
then
maxVal=${scores[$j]}
maxIndex=$j
fi
fi
done
a1[${#a1[*]}]=$maxVal
a2[${#a2[*]}]=${names[$maxIndex]}
unset scores[$maxIndex]
done
for(( i=0; j<${#a2[*]} && i < ${#a1[*]; i++ ))
do
echo ${a2[i]} ${a1[i]}
done
#10.Print sorted names and scores. Put the rank of each student before the
m=${#names[*]}
n=${#scores[*]}
for (( i=0; i<$n && i<$m; i++ ))
do
maxVal=1
maxIndex=0
for (( j=0: j<$n && j<$m; j++ ))
do
if [[ !_-z ${scores[$j]}) ]]
then
if (( $maxVal < ${scores[$j]}
maxIndex=$j
fi
fi
done
a1[${#a1[*]}]=$maxVal
a2[${#a2[*]}=${names[$maxIndex]}
unset scores[$maxIndex]
done
k=1
while [[ $k -lt ${#a2[*]} ]]
do
for(( i=0;i < ${#a2[*]} && i < ${#a1[*]};i++ ))
do
echo "Ranking" $k "is:" ${a2[i]}
k=$(($k+1))
done
done
Like you can see in your line, just before the then one, you mixed single and double quotes:
echo "inputfile is not a file'
Just replace the final simple quote, by a double one.

Create sequential numbers in loop

I need a bash script which can generate 4500 numbers in sequence and feed it as an input to an executable and repeat the process by creating next 4500 numbers and again feed to the same executable.
The script should exit once more than 90000 numbers are generated.
Right now I am using:
i=1
while [ "$i" -le 90000 ]; do
C:/Python27/Scripts/bu.exe "$i"
i=$(($i+1))
done
which inputs one number at a time and is a time consuming process.
Any help will be gratefully appreciated.
Thanking you and regards.
$ for (( i=1; i<12; i+=3 )); do printf '####\n'; seq "$i" "$(( i+2 ))"; done
####
1
2
3
####
4
5
6
####
7
8
9
####
10
11
12
Replace the numbers above with your real values and depending on what it is you're really trying to do either pipe the seq output to your command:
$ for (( i=1; i<12; i+=3 )); do seq "$i" "$(( i+2 ))" | my_command; done
or call your command with the seq output as it's arguments:
$ for (( i=1; i<12; i+=3 )); do my_command $(seq "$i" "$(( i+2 ))"); done
I would rather advise you to execute it parallel like below. My below modification will execute 10 processes in parallel and will reduce your execution time. Please keep in mind parallel execution also depends on number of processors and memory in your system.
i=1
j=0
while [ "$i" -le 90000 ]; do
C:/Python27/Scripts/bu.exe "$i" &
# Now you are executing parallel
j=$(($j+1))
#if 10 parallel process has been created just wait to complete them
# and re-start the parallel process again
if [ $j -ge 10 ]; then
wait
j=0
fi
i=$(($i+1))
done
I read somewhere that running $(seq) is expensive (in the context of that discussion, not related to this question) so I decided to test running the seq while the bu.exe is running in the background:
for (( i=1 ; $((j=i+4499))<=90000 ; i+=4500)) # 1...4500, 4501...9000 etc.
do
parms=$(seq -s " " $i $j) # set the parameters to var
wait $pid # wait for the previous bu.exe
bu.exe "$parms" & # execute bu.exe in the bg
pid=$! # store pid
done

var+= adds string instead of sum

I have to make a script that makes the sum of all processes that have PIDS greater than 20. It kind of works but something is going wrong. I know it's something simple, base thing, but I can't get the logic.
For example I have 2 processes, "1504" and "1405". My result of sum is 15041405. How do I have to re-write sum+=${proc[$i]} to make an actual sum, not string attach?
proc=( $(ps | cut -d ' ' -f1) )
nr=$(ps | cut -d ' ' -f1 | wc -l)
sum=0
for (( i=0 ; i<=nr ; i++)); do
[[ ${proc[$i]} -gt 20 ]] && sum+=${proc[$i]}
done
echo $sum
Use a math context. In POSIX sh:
sum=$(( sum + val ))
...or, also valid POSIX:
: "$(( sum += val ))"
...or, in bash:
(( sum += val ))
You can also use much easier-to-read comparison operations in a math context, rather than using -gt inside of a non-math test context. In bash:
(( ${proc[$i]} >= 20 )) && (( sum += ${proc[$i]} ))
...or in POSIX shell (which doesn't support arrays, and so cannot exactly reproduce your sample code):
: "$(( sum += ( val < 20 ) ? 0 : val ))"
If you were trying to do the (more sensible) operation of counting PIDs, I'd consider an implementation more like the following (bash-only and Linux-only, but considerably more efficient):
count=0
for pid_file in /proc/[0-9]*; do
pid=${pid_file##*/}
(( pid > 20 )) && (( count++ ))
done
printf '%s\n' "$count"
...or, to put more of the effort on the glob engine:
# avoid inflating the result with non-matching globs
shopt -s nullglob
# define a function to avoid overwriting the global "$#" array
count_procs() {
set -- /proc/[3-9][0-9] /proc/[0-9][0-9][0-9]*
echo "$#"
}
# ...used as follows:
count_procs

Parameter input works, but pipe doesn't

I tried to create a shell script, which sum the given numbers. If there is no given parameter, then it tries to read the pipe output, but I get an error.
#!/bin/sh
sum=0
if [ $# -eq 0 ]
then
while read data
do
sum=`expr $sum + $data`
done
else
for (( i = 1 ; i <= $#; i++ ))
do
sum=`expr $sum + ${!i}`
done
fi
echo $sum
This works: sum 10 12 13
But this one doesn't: echo 10 12 13| sum
Thanks in advance,
Here you go (assuming bash, not sh):
#!/bin/bash
sum=0
if (( $# == 0 )); then
# Read line by line
# But each line might consist of separate numbers to be added
# So read each line as an array!
while read -a data; do
# Now data is an array... but if empty, continue
(( ${#data[#]} )) || continue
# Convert this array into a string s, with elements separated by a +
printf -v s "%s+" ${data[#]}
# Append 0 to s (observe that s ended with a +)
s="${s}0"
# Add these numbers to sum
(( sum += s ))
done
else
# If elements come from argument line, do the same!
printf -v s "%s+" $#
# Append 0 to s (observe that s ended with a +)
s="${s}0"
# Add these numbers to obtain sum
(( sum = s ))
fi
echo $sum
You can invoke it thus:
$ echo 10 12 13 | ./sum
35
$ ./sum 10 12 13
35
$ # With several lines and possibly empty lines:
$ { echo 10 12 13; echo; echo 42 22; } | ./sum
99
Hope this helps!
Edit. You might also be interested in learning cool stuff about IFS. I've noticed that people tend to confuse # and * in bash. If you don't know what I'm talking about, then you should use # instead of *, also for array subscripts! In the bash manual, you'll find that when double quoted, $* (or ${array[*]}) expands to all the elements of the array separated by the value of the IFS. This can be useful in our case:
#!/bin/bash
sum=0
if (( $# == 0 )); then
# Read line by line
# But each line might consist of separate numbers to be added
# So read each line as an array!
while read -a data; do
# Now data is an array... but if empty, continue
(( ${#data[#]} )) || continue
# Setting IFS=+ (just for the sum) will yield exactly what I want!
IFS=+ sum=$(( sum + ${data[*]} ))
done
else
# If elements come from argument line, do the same!
# Setting IFS=+ (just for the sum) will yield exactly what I want!
IFS=+ sum=$(( $* ))
fi
echo $sum
Gniourf now exits from teacher mode. :-)

Resources