0

so i have this code here:

    #!/bin/bash
sum=0
for i;
do 
   if [ "$i" -ge 0 ]
   then
       sum=$((sum + i))
   else
       sum=$((sum + (i * -1)))
   fi
done
echo $sum

so the user types blin.sh 1 3 2 5 -5 -8, and the program is supposed to take all of the integers, and make them positive, if it is a negative, and then echo the sum. but my bash code only echo's 0 for some reason unknown to science.

15
  • Why is this tagged python? Commented May 5, 2020 at 2:30
  • And why do you talk about command line arguments when your script looks at filenames instead? Commented May 5, 2020 at 2:31
  • file names?, how can i make it to where i takes in a integer?? Commented May 5, 2020 at 2:32
  • Because the file names are included in the loop instead of the arguments..., stdin_data and stdout_data are both files that are in the same directory where you execute that script..., Do you know how to access the arguments/positional parameter in a bash shell script? The glob * expands to all files/directories in the current directory... Commented May 5, 2020 at 2:43
  • 1
    execute as sh -x blin.sh 1 3 2 5 -5 -8 This will print all command execution on stdout Commented May 5, 2020 at 3:45

2 Answers 2

1

Here is an example of your script.

#!/bin/bash

sum=0
for i ; do
   if [ "$i" -ge 0 ]
   then
      sum=$((sum + i))
   else
      sum=$((sum + (i * -1)))
   fi
done
echo $sum

The name of the script is foo.sh, Now execute that script with the arguments.

./foo.sh  1 3 2 5 -5 -8

Out put

24

Using sh

sh ./foo.sh  1 3 2 5 -5 -8

Out put

24

Using dash

dash ./foo.sh  1 3 2 5 -5 -8

Output

24

Using zsh

zsh ./foo.sh  1 3 2 5 -5 -8

Output

24

I don't see any errors there.

Sign up to request clarification or add additional context in comments.

Comments

1

use $* for all arguments (without the semicolon ;)

for i in $*

your code works for me.

#!/bin/bash
sum=0
for i in $*
do
        if [ "$i" -ge 0 ] 
        then
                sum=$((sum + i))
        else
                sum=$((sum + (i * -1)))
        fi
done
echo $sum

enter image description here

2 Comments

still nothing, it only returns zero, can you try it??
can you help me please?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.