Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with program check if the number is divisible by 2 with no remainder BASH

Tags:

bash

division

I tried to write a program to see if the count divisible by 2 without a remainder Here is my program

count=$((count+0))

while read line; do

if [ $count%2==0 ]; then
    printf "%x\n" "$line" >> file2.txt
else
    printf "%x\n" "$line" >> file1.txt
fi

count=$((count+1))
done < merge.bmp

This program doesnt work its every time enter to the true

like image 777
Aviel Ovadiya Avatar asked Oct 16 '25 22:10

Aviel Ovadiya


2 Answers

In the shell, the [ command does different things depending on how many arguments you give it. See https://www.gnu.org/software/bash/manual/bashref.html#index-test

With this:

[ $count%2==0 ]

you give [ a single argument (not counting the trailing ]), and in that case, if the argument is not empty then the exit status is success (i.e. "true"). This is equivalent to [ -n "${count}%2==0" ]

You want

if [ "$(( $count % 2 ))" -eq 0 ]; then

or, if you're using bash

if (( count % 2 == 0 )); then
like image 75
glenn jackman Avatar answered Oct 18 '25 13:10

glenn jackman


Some more "exotic" way to do this:

count=0
files=(file1 file2 file3)
num=${#files[@]}

while IFS= read -r line; do
    printf '%s\n' "$line" >> "${files[count++ % num]}"
done < input_file

This will put 1st line to file1, 2nd line to file2, 3rd line to file3, 4th line to file1 and so on.

like image 31
PesaThe Avatar answered Oct 18 '25 13:10

PesaThe