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.
All levels of question are accepted here.
You can use
awkto only get the first field:Your script would then be something like:
You’ll notice I’ve changed a couple of other things as well:
$(X)to `X` for capturing output of command simply because they’re easier to nest.$1into$filename, you may as well use$filenamefrom that point on (the$1in theawkis a different beast).${}so that it’s obvious to both the reader and the shell that${var}Xis$varappended withX, 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 🙂