I just started learning bash. I know there are advanced ways of solving this problem but I can't use any advanced methods. I recently finished a lecture on loops and I'm expected to know how to solve this. But after 3+ hours of reading I can't find a solution.
Here's the prompt:
Create a script that will take in x amount of numbers from a user (minimum 5 numbers) via the use of positional variables. Then do the following:
Count how many numbers were inputted
Add up all the numbers
Multiply all the numbers
Find the average of all the numbers
read -p "Enter at least 5 integers"
#Check to make sure integers entered are indeed integers (how?)
#Check to make sure at least 5 integers were entered (how?)
#for total number of integers entered, add into a sum
#for total number of integers entered, find total product
#find average of all integers entered
My main issues are with the checks. Also, how do I assign an indefinite number of values to variables? Thanks for any help. I've looked around but have found no beginner solution to this.
#!/bin/bash
declare -i sum=0
declare -i counter=0
declare -i product=1
if [[ $# -lt 5 ]]
then
echo "Please enter atleast 5 positional parameters"
exit 1
fi
for num in "$#" #$# means all positional parameters, $1, $2, $3 and so on
do
#checking if the entered positional parameters are digits using regular expression, [0-9]+ means match any digit 1 or more times
if [[ "$num" =~ ^[0-9]+$ ]]
then
sum=$(($sum+$num))
product=$(($product*$num))
((counter++))
else
echo "$num is not a number"
fi
done
echo
echo "Result: "
echo "count of numbers: $counter"
echo "sum of numbers: $sum"
echo "average of numbers: "$(echo "scale=4;$sum/$counter" | bc)
echo "product of numbers: $product"
Output:
$ ./script.bash 1 2 3 4 5 abcd
abcd is not a number
Result:
count of numbers: 5
sum of numbers: 15
average of numbers: 3.0000
product of numbers: 120
$ ./script.bash 1 2 3
Please enter atleast 5 positional parameters
$ ./script.bash 56 78 235 67 466
Result:
count of numbers: 5
sum of numbers: 902
average of numbers: 180.4000
product of numbers: 32048758560
Related
I am messing around with something on bash (I am very new to it).
I have a floating point number.
I want to to be able to check if there is any digits after the decimal point from 1-9 in order to determine whether it is a whole number - and do it within an if-else statement.
for example
if(*number does have a 1-9 digit after decimal*)
then
echo 'Number is not a whole number'
else
echo 'Number is a whole number'
fi
Dabbled with grep and REGEX but don't have a great grasp of it yet
With a regex:
x=1.123456789
if [[ "$x" =~ \.[0-9]{1,9}$ ]]; then
echo 'Number is not a whole number'
else
echo 'Number is a whole number'
fi
Output:
Number is not a whole number
Mac_3.2.57$cat findWhole.bash
#!/bin/bash
for x in 1.123456789 0001230045600.00 1.000000 1 1. 1.. 0002 .00 22.00023400056712300 1.00 .
do
if [[ "$x" =~ ^[0-9]*\.[0-9]*[1-9][1-9]*[0-9]*$ ]]; then
echo "$x is not a whole number"
elif [[ "$x" =~ ^[0-9][0-9]*\.?0*$|^\.00*$ ]]; then
echo "$x is a whole number"
else
echo "$x is not a number"
fi
done
Mac_3.2.57$./findWhole.bash
1.123456789 is not a whole number
0001230045600.00 is a whole number
1.000000 is a whole number
1 is a whole number
1. is a whole number
1.. is not a number
0002 is a whole number
.00 is a whole number
22.00023400056712300 is not a whole number
1.00 is a whole number
. is not a number
Mac_3.2.57$
I'm trying to write a script that takes integers as command line arguments, squares them and then shows the squares and the sum of the squares. Here's what I have:
#!/bin/bash
if [ $# = 0 ]
then
echo "Enter some numbers"
exit 1
fi
sumsq=0 #sum of squares
int=0 #Running sum initialized to 0
count=0 #Running count of numbers passed as arguments
while (( $# != 0 )); do
numbers[$int]=$1 #Assigns arguments to integers array
square=$(($1*$1)) #Operation to square argument first arg by itself
squares[$int]=$square #Square of each argument
sumsq=$((sumsq + square)) #Add square to total
count=$((count+1)) #Increment count
shift #Remove the used argument
done
echo "The squares are ${squares[#]}"
echo "The sum of the squares is $sumsq"
exit 0
I have it all working as it should except for the end where I need to display the squares. It is only printing the last square for some reason. I've tried changing e${squares[#]}" to ${squares[*]}", as well as double-quoting it, but it still only prints the last square. At some point, it printed the first square (which is expected) but I must have made a change somewhere and now it only seems to print the last one.
Any advice would be appreciated. Thanks!
The easy thing to do is simply delete the int variable altogether and replace it with count which you already increment within your loop, e.g.
sumsq=0 #sum of squares
count=0 #Running count of numbers passed as arguments
while (( $# != 0 )); do
numbers[$count]=$1 #Assigns arguments to integers array
square=$(($1*$1)) #Operation to square argument first arg by itself
squares[$count]=$square #Square of each argument
sumsq=$((sumsq + square)) #Add square to total
count=$((count+1)) #Increment count
shift #Remove the used argument
done
Example Use/Output
Making the change above:
$ bash squares.sh 1 2 3 4
The squares are 1 4 9 16
The sum of the squares is 30
(no, you don't such at programming, that's one issue new script writers could stare at for hours and not see -- and why running with bash -x scriptname to debug is helpful)
Update Following Comment Re: Difficulty
Above I only posted the changes needed. If it is not working for you, then I suspect a typo somewhere. Here is the complete script you can simply save and run:
#!/bin/bash
if [ $# = 0 ]
then
echo "Enter some numbers"
exit 1
fi
sumsq=0 #sum of squares
count=0 #Running count of numbers passed as arguments
while (( $# != 0 )); do
numbers[$count]=$1 #Assigns arguments to integers array
square=$(($1*$1)) #Operation to square argument first arg by itself
squares[$count]=$square #Square of each argument
sumsq=$((sumsq + square)) #Add square to total
count=$((count+1)) #Increment count
shift #Remove the used argument
done
echo "The squares are ${squares[#]}"
echo "The sum of the squares is $sumsq"
exit 0
As per the example above, run the script as:
bash squares.sh 1 2 3 4
(replace squares.sh with whatever name you gave to the file) If you have any problems, let me know because this is working quite well here, e.g.
bash squares.sh 1 2 3 4 5 6 7 8 9
The squares are 1 4 9 16 25 36 49 64 81
The sum of the squares is 285
Try this.
#!/usr/bin/env bash
case $# in
0) printf 'give me something!' >&2; exit 1;; ##: If no argument given exit!
esac
sumsq=0 #sum of squares
int=0 #Running sum initialized to 0
count=0 #Running count of numbers passed as arguments
while (( $# )); do
case $1 in
*[!0-9]*) printf '%s is not an integer!' >&2 "$1" ##: If argument is not an int. exit!
exit 1;;
esac
numbers[$((int++))]=$1 #Assigns arguments to integers array increment int by one
square=$(($1*$1)) #Operation to square argument first arg by itself
squares[$((int++))]=$square #Square of each argument increment int by one
sumsq=$((sumsq + square)) #Add square to total
count=$((count++)) #Increment count
shift #Remove the used argument
done
echo "The squares are ${squares[#]}"
echo "The sum of the squares is $sumsq"
Just iterate over given arguments
#!/bin/bash
for N in "$#"; { # iterate over args
squares+=( $((N*N)) ) # will create and then apend array squares
}
sqstr="${squares[#]}" # create string from array
echo "The squares are $sqstr" # string of squares will be substituted
echo "The sum of the squares is $((${sqstr// /+}))" # string will be substituted,
# spaces will be changed to +
# and sum will be calculated
Usage
$ ./test 1 2 3 4 5
The squares are 1 4 9 16 25
The sum of the squares is 55
Updated version
#!/bin/bash
for N do squares+=($((N*N))); done # iterate over args, create and then apend array squares
sqstr="${squares[#]}" # create string from array
echo "The squares are $sqstr" # string of squares will be substituted
echo "The sum of the squares is $((${sqstr// /+}))" # string will be substituted,
# spaces will be changed to +
# and sum will be calculated
i´m new to scripting and bash.
I need help with bash script (for cycle)
I´ve got a script called for.sh
It has to ask 10 numbers from user with for cycle.
In every cycle number will be divided with 3 or 5.
If it divides it will say it.
My idea was to use read, for i in $(eval echo "$numbers") and if commands but that does not seem to work.
This can be achieved by for as well as while loop.
using for loop here:
#!/bin/bash
for (( i=1; i<=10; i++ ))
do
read -p "Enter the number:" num
if [[ $(($num%3)) -eq '0' ]]
then
echo "$num is divisible by 3"
elif [[ $(($num%5)) -eq '0' ]]
then
echo "$num is divisible by 5"
else
echo "$num is not divisible by either 3 or 5"
fi
done
I've initialized a variable i to 1, so everytime the for loop will run ,it'll ask the number from the user, store it into another variable called num and then check if the entered number is divisible by 3 or 5, if the entered number is not divisible by 3 or 5, it will say "number is not divisible by either 3 or 5".
With every run, the for loop will increment the count by 1 till it reaches the count=10.
I am a bash newbie. I would like to echo the numbers 1 to x in a n digits format. For example, let's consider n=3: 5 should become 005, 13 should become 013, 110 should remain 110.
One way to achieve this is with this kind of structure:
for i in $(seq 1 120)
do
if [ "$i" -lt "10" ]
then
echo "00$i"
elif [ "$i" -gt "99" ]
then
echo "$i"
else
echo "0$i"
fi
done
but it is quite ugly and is really not flexible to changing values of n (number of digits). I'd rather have a function that just do the formatting in n digits? Is there an already built in function for that? If not can you help me to create such function?
Use printf:
for i in {1..120} ; do
printf '%03d\n' $i
done
% starts the format string
d means integer
3 means length = 3
0 means zero padded
\n is a newline
I'm writing a mathematical toolkit consisting of various commands. One of the commands I would like to write is for finding the factors of a 3 digit number. Please name the command as “myfactors”. Here’s an example transcript:
$ myfactors abc
abc is not a number. Please enter a number
$ myfactor 72
72 is not a 3 digit number
$ myfactor 105
The factors are: 1 3 5 7 15 21 35 105
Please check this, I used factor GNU tool available In Ubuntu.
#!/bin/bash
num=$1
if [ "$num" -ge 100 ]
then
factor="`factor $num`"
echo "Factor of number $num is $factor"
else
echo "Enter number is not a 3 digit number"
fi
Or you we make it more restrictive to accept only 3 digit numbers
#!/bin/bash
num=$1
if [ "$num" -ge 100 ] && [ "$num" -lt 1000 ]
then
factor="`factor $num`"
echo "Factor of number $num is $factor"
else
echo "Enter number is not a 3 digit number"
fi