-1

I cant get this simple program working the code looks like this because is for a class exercise I wouldn't do it like that but I have to, sorry if the code is a mess but I've tried so many things that the code is a bit "deformed"

n= 0
for x in /home
do
e= du $x -B1 | cut d" " -f 1
$sum$(($sum+$e))
done
echo $sum
5
  • So.. what is it you're trying to do? Commented Jan 27, 2019 at 17:25
  • to add the value one by one of the contents of /home to the value of sum and print it in the console Commented Jan 27, 2019 at 17:32
  • Add echo $x after the line with do and try to wonder what is the use of for? You can also add echo $sum to understand the error. Commented Jan 27, 2019 at 17:43
  • Consider running your code through shellcheck.net and fixing what it finds before asking questions here. Commented Jan 27, 2019 at 18:46
  • In the duplicate about looping over directories, see in particular the answer by ghostdog74 at stackoverflow.com/a/2108296/14122 (but don't copy their unquoted echo argument; that's bad form). Several of the bugs here can also be found in BashPitfalls; consider it recommended reading. Commented Jan 27, 2019 at 18:47

1 Answer 1

1

At line 1 you have a space between the '=' and the 0, but there shouldn't be a spaces either before or after the '=' in an assignment.

At line 4 happens the same, but also you missed the backticks '`' around the commands, that indicate bash to evaluate what is inside the backticks and return the output of that command.

At line 5 it says:

$sum$(($sum+$e))

So did you mean:

sum=$(($sum+$e))

Update: I have found three problems more:

In line 2, replace /home with /home/*, because the former only uses /home in the loop, and the later returns every directory (and file) in the /home directory.

You are passing d" " to cut, the correct option is -d " ".

Also, du output is formatted with tabs, not spaces. If you delete the -d " " in cut, it works.

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

5 Comments

i've applied all the things you say, it does not work, same error. i dont know why it does not take the operation.
Please don't even mention backticks. The recommended form of command substitution is $(...).
@mamg22 See stackoverflow.com/help/how-to-answer, particularly the section "Answer Well-Asked Questions" -- questions that don't focus on a single, narrow, specific bug should be closed, not answered.
Also, -d" " is perfectly valid. Even though the POSIX cut spec shows the option-argument separated on the cut page, see the last sentence of 2a in the Utility Argument Syntax specification noting that option-arguments do not strictly require that space.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.