7

When I type sudo du -sh ~student1 I get the output I expect (see screenshot). However when I try to use the script below:

#!/bin/bash

for user in "$@"; do
    sudo du -sh ~$user
done

to do the same thing, I get an error that the directory doesn't exist. Here is a screenshot.

(I know I can do sudo du -sh student1 student2..., and that the bash script is useless but I still don't understand why it doesn't work.)

I had a look at Total disk usage for a particular user but it wasn't quite what I was looking for.

kg98
  • 73

3 Answers3

4

The shell does a single pass on expanding parameters, so $user is expanded, but the preceding ~ isn't then expanded. In order to reparse the input line, use eval:

...
eval sudo du -sh ~$user
...
AFH
  • 17,958
0
find . -printf "%u  %s\n" | awk '{user[$1]+=$2}; END{ for( i in user) print i " " user[i]}'

this will print

jsmith 928057466

the same function

find . -user jsmith -type f -printf "%s\n" | awk '{t+=$1}END{print t}'

this will print just

928057466

Joniale
  • 101
  • 2
0

As mentioned by @AFH, the tilde (~) isn't expanded, and you could use eval to handle this...

Or you could use getent to get a user's home directory:

$ getent passwd attie | cut -d: -f6
/home/attie

This way it would be easier to detect an error (rather than a mysterious variable expansion issue).

You could even use this to enumerate user directories:

$ getent passwd | cut -d: -f6 | grep -E '^/home/'
/home/attie
/home/bill
Attie
  • 20,734