Post: Bash scripting help!
11-28-2014, 09:10 PM #1
jagex
Gym leader
(adsbygoogle = window.adsbygoogle || []).push({});
    
#!/bin/bash
sum=0
for number in $@
do

echo $number | grep "[^a-z]"

if [ $? != 0 ]
then
echo "Sorry, '$number' is not a number"

else

sum=$((sum + number))
echo "$sum"

fi

done


So I type add2 5 2 and I get
5
5
2
7
I type add2 5 twelve nine 5 I get
Sorry, 'twelve' is not a number
Sorry, 'nine' is not a number
5
5
but my assignment wants me to exactly print this message out but im not sure how to do it because if I remove echo from the pipe command it won't work
add2 4 -3 12 9
22
add2 4 -3 twelve nine
twelve
Sorry, 'twelve' is not a number
(adsbygoogle = window.adsbygoogle || []).push({});
11-30-2014, 11:55 AM #2
Default Avatar
Oneup
Guest
Originally posted by jagex View Post
    
#!/bin/bash
sum=0
for number in $@
do

echo $number | grep "[^a-z]"

if [ $? != 0 ]
then
echo "Sorry, '$number' is not a number"

else

sum=$((sum + number))
echo "$sum"

fi

done


So I type add2 5 2 and I get
5
5
2
7
I type add2 5 twelve nine 5 I get
Sorry, 'twelve' is not a number
Sorry, 'nine' is not a number
5
5
but my assignment wants me to exactly print this message out but im not sure how to do it because if I remove echo from the pipe command it won't work
add2 4 -3 12 9
22
add2 4 -3 twelve nine
twelve
Sorry, 'twelve' is not a number

When I run this I actually get different results.

One the first run I get:
Originally posted by another user

0
5
5
2
7

Any ways I am not entirely sure what you are asking. You are displaying the error that you want correct? Or are you trying to display the error without using grep?

If so you can do this

    
#!/bin/bash
sum=0
regEX='^[0-9]+$'
for number in $@
do


if ! [[ $number =~ $regEX ]] ; then
echo "Sorry, '$number' is not a number"

else
echo "Current Number: '$number' "
sum=$((sum + number))
echo "$sum"

fi

done
11-30-2014, 10:02 PM #3
jagex
Gym leader
Originally posted by 1UP View Post
When I run this I actually get different results.

One the first run I get:

Any ways I am not entirely sure what you are asking. You are displaying the error that you want correct? Or are you trying to display the error without using grep?

If so you can do this

    
#!/bin/bash
sum=0
regEX='^[0-9]+$'
for number in $@
do


if ! [[ $number =~ $regEX ]] ; then
echo "Sorry, '$number' is not a number"

else
echo "Current Number: '$number' "
sum=$((sum + number))
echo "$sum"

fi

done


I managed to fix it, I had echo "$sum" in the for loop so it kept printing out the numbers during each loop and my assignment wouldn't accept that
11-30-2014, 10:02 PM #4
jagex
Gym leader
I managed to fix it, I had echo "$sum" in the for loop so it kept printing out the numbers during each loop and my assignment wouldn't accept that

0
5
5
2
7

It should only print out 7

Copyright © 2026, NextGenUpdate.
All Rights Reserved.

Gray NextGenUpdate Logo