Alex
Alex

Reputation: 2299

Removing the file part of the output from du in a bash script

I'm trying to remove the output when calling du in my bash script. I'm just trying to print out the size of the current directory. So it looks like this:

DIRSIZE=$(du -hs $1)
printf "The size of the directory given is: %s\n" "$DIRSIZE"

I want the output to look like this:

The size of the directory given is: 32K

However, my command currently outputs:

The size of the directory given is: 32K /home/dir_listed/

Is there an easy way to remove the directory?

Upvotes: 0

Views: 1250

Answers (2)

Arjun Mathew Dan
Arjun Mathew Dan

Reputation: 5298

With awk:

DIRSIZE=$(du -hs $1 | awk '{print $1}')

Take only the first field from du output and save to DIRSIZE.

With sed:

DIRSIZE=$(du -hs $1 | sed 's/[[:space:]].*//')

Remove from first space to end of line and save to DIRSIZE.

With cut:

DIRSIZE=$(du -hs $1 | cut -f 1)

Take only the first field from du output which is tab seperated and save to DIRSIZE.

Upvotes: 2

CloudGuy
CloudGuy

Reputation: 120

Try this:

DIRSIZE=$(du -hs $1 | awk '{print $1}')
printf "The size of the directory given is: %s\n" "$DIRSIZE"

Upvotes: 2

Related Questions