0

Im trying to run trough a directory showing file sizes, but when i try to print the size of a file that has spaces stat command fails. How can i fix this?

#!/bin/bash

    for file in /home/user/Desktop/*; do
        fileSize=$(stat -c%s $file)
        echo $fileSize
    done
  • Simply `stat -c%s /home/user/Desktop/*` would do what you want; but printing just the size without the file name is pretty useless anyway. Probably include the file name in the format string. – tripleee Nov 09 '18 at 05:17

2 Answers2

0

You should add quotes around variables to make sure if there are spaces in there that they get picked up correctly:

#!/bin/bash

for file in /home/user/Desktop/*; do
    fileSize=$(stat -c%s "$file")
    echo $fileSize
done

What bash does is it simply replaces $var with the thing in $var. If that contains spaces it becomes something else then you intended, because spaces are used in bash to separate command options.

Consider the following example:

file="-l -h -a -F"
ls $file

This gets parsed as:

ls -l -h -a -F

The output will not be the just the file "-l -h -a -F" but it will get parsed as options for ls and it will show the current directory listing. If you had put quotes around $file like so:

file="-l -h -a -F"
ls "$file"

It will get parsed like:

ls "-l -h -a -F"

ls will search for the file "-l -h -a -F" and show only that one file (assuming it exists, it errors otherwise).

Veda
  • 2,025
  • 1
  • 18
  • 34
0

Use quotes.

#!/bin/bash
for file in /home/user/Desktop/*; do
    fileSize=$(stat -c%s "$file")
    echo $fileSize
done

Adjusted for my desktop -

$: for file in *
   do case "$f" in
      *\ *) printf "'$f': %d\n" $(stat -c%s "$file")
      esac
   done
'BPS Stuff': 0
'New TWC Account -  Hodges  Paul A.msg': 37888
'Nov FTOTD calendar.JPG': 138769
'OCA Web Client - ASAP.lnk': 2406
'Paul - Copy.png': 64915
'Solstice Client.lnk': 2165
'VIP Access.lnk': 2079
Paul Hodges
  • 13,382
  • 1
  • 17
  • 36