0

I am a newbie to BASH so please dont mind my stupid questions because I am not able to get any good sources to learn that.

I want to create a script to display filename and its size. This is what the code is like

filename=$1
if [ -f $filename ]; then
    filesize=`du -b $1`
    echo "The name of file is $1"
    echo "Its size is $filesize"
else
    echo "The file specified doesnot exists"
fi

The output is like this

$ ./filesize.sh aa
The name of file is aa
Its size is 88  aa

But in the last line I don't want to show the name of the file. How do I do that ? I want to do the same thing using wc as well.

1

6 Answers 6

3

Use stat(1)

filename=$1
if [ -f $filename ]; then
    filesize=`stat -c %s $1`
    echo "The name of file is $1"
    echo "Its size is $filesize"
else
    echo "The file specified doesnot exists"
fi

See also man 1 stat

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

1 Comment

I like this solution the best: It employs only one external tool (stat), unlike other solutions which use two.
1
filesize=`du -b $1 | cut -f 1`

cut -f 1 splits its input by tabs and then outputs the first field (i.e. it returns each line of du's output up to the fist tab character.).

Comments

0

All levels of question are accepted here.

You can use awk to only get the first field:

du -b /path/to/file | awk '{print $1}'

Your script would then be something like:

filename=$1
if [ -f ${filename} ]; then
    filesize=$(du -b ${filename} | awk '{print $1}')
    echo "The name of file is ${filename}"
    echo "Its size is ${filesize}"
else
    echo "The file specified does not exists"
fi

You'll notice I've changed a couple of other things as well:

  • I prefer $(X) to `X` for capturing output of command simply because they're easier to nest.
  • If you've already put $1 into $filename, you may as well use $filename from that point on (the $1 in the awk is a different beast).
  • I prefer to put all my variables inside ${} so that it's obvious to both the reader and the shell that ${var}X is $var appended with X, rather than $varX being the non-existent ${varX}.

These are really personal preferences but, as with all my personal preferences, I consider them best practices for the entire IT industry :-)

Comments

0

You could use awk to split the output of du at the first space, as follows:

filesize=`du -b $1 | awk '{ print $1; }'`

Comments

0

Instead of using du -b $1 use du -b $1 | cut -f 1. It will only include the first field of output of du command, therefore only reporting the size of the file.

Comments

0

You can use awk to pick out the first column of data.

filesize=`du -b $1 | awk '{print $1}'`

Comments

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.