I am in a middle of an assignment and i would appreciate any help.
How can i write a bash shell script code that checks if all elements in an array are the same numbers. I mean -->array = ( 0,0,0,0,0 )
( e.g., if [ #all array elements equal zero ]
then return "OK'
fi )
#!/bin/bash
array=( 0 0 0 0 0 )
flag=0
for i in "${array[@]}"; do
if [ $i -ne 0 ]; then
flag=1
fi
done
if [ $flag = "1" ]; then
echo "not OK"
else
echo "OK"
fi
#! /bin/bash
arr=( 2 2 2 2 2 )
e=${arr[0]}
for x in ${arr[@]}
do
if [ $x -eq $e ]
then
flag=1
continue
else
flag=0
break
fi
done
if [ $flag -eq 1 ]
then
echo "OK"
else
echo "Not OK"
fi
Hi Jotne, it takes the first element of the array and deletes the first portion of each element if that portion matches that first element. If all elements in array A are equal, then this will result in an array of empty strings. This result is then assigned to a variable, after which the variable should contain all non-empty array elements separated by spaces.
So if all array elements are identical, then the result should be an array of empty strings and then the variable should contain an empty string.
Oh dear, I must have somehow missed that you seem to be talking about a homework assignment.
Do not post classroom or homework problems in the main forums. Homework and coursework questions can only be posted in this forum under special homework rules. Please review the rules, which you agreed to when you registered, if you have not already done so and please review the guidelines for posting homework.