2
size=`ls -l /var/temp.* | awk '{ print $5}'`
        fin_size=0
        for row in ${size} ;
        do      
                 fin_size=`echo $(( $row + $fin_size )) | bc`;
        done
echo $fin_size

is not working !! echo $fin_size is throwing some garbage minus value. where I'm mistaking? (my bash is old and I suppose to work in this only Linux kernel: 2.6.39)

1
  • 1
    As dogbane suggested, you should never parse the output of ls (read here why), so this and the accepted answer is the wrong approach to your problem. Use du, stat or find. Commented May 13, 2013 at 10:51

3 Answers 3

2

Don't parse ls.

Why not use du as shown below?

du -cb /var/temp.* | tail -1 
Sign up to request clarification or add additional context in comments.

2 Comments

+1 for the link to Greg's wiki and the du suggestion; just noting that tail -1 is deprecated and you should use tail -n 1 instead.
why it is giving more values than 'ls parse' ? for eg. above answer is 931234 and with this command its 951252
1

Because it cannot be stressed enough: Why you shouldn't parse the output of ls(1)

Use e.g. du as suggested by dogbane, or find:

$ find /var -maxdepth 1 -type f -name "temp.*" -printf "%s\n" | awk '{total+=$1}END{print total}'

or stat:

$ stat -c%s /var/temp.* | awk '{total+=$1}END{print total}'

or globbing and stat (unnecessary, slow):

total=0
for file in /var/temp.*; do
    [ -f "${file}" ] || continue
    size="$(stat -c%s "${file}")"
    ((total+=size))
done
echo "${total}"

3 Comments

Piping the output of find to awk will fail under the same circumstances that piping the output of ls will fail: when the file name contains a newline character.
@chepner You did not look closely enough, I am only outputting the size of the files in question.
@chepner No worries. Probably my fault for not explaining the code.
-1

Below should be enough:

ls -l /var/temp.*  | awk '{a+=$5}END{print a}'

No need for you to run the for loop.This means:

size=ls -l /var/temp.* | awk '{ print $5}'`
        fin_size=0
        for row in ${size} ;
        do      
                 fin_size=`echo $(( $row + $fin_size )) | bc`;
        done
echo $fin_size

The whole above thing can be replaced with :

fin_size=`ls -l /var/temp.*  | awk '{a+=$5}END{printf("%10d",a);}'`
echo $fin_size

4 Comments

answer is : 2.61708e+09 I need like 1234341231
change the print a to printf ("%10d",a);
Somebody has given..not me
The downvote is probably for parsing the output of ls; it's not guaranteed to work in all cases, and should not be suggested as an answer.

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.