-   Linux - General (
-   -   use of ls command (

Micky12345 02-27-2012 10:56 PM

use of ls command
using ls command i want to find the total size of all regular files

ls -l | grep '^-' | cut -d " " -f6
when i tried with above code i got size of only a few files

how can i get the size of all files and their total

catkin 02-27-2012 11:39 PM

ls output should not be parsed for reasons explained here.

Safer to use something like this which also copes with file names having unusual characters in their names such as backspace and linend. Not tested.

while IFS= read -r -d '' file
  (( size += $( stat --format=%s "$file" ) ))
done < <(find . -maxdepth 0 -type f -print0)
echo "Total size is $size bytes"

Micky12345 02-28-2012 01:43 AM

i didn't understand the meaning of

IFS= read -r -d '' file
and also

$( stat --format=%s "$file" )
done < <(find . -maxdepth 0 -type f -print0)

can u tell me if u don't mind

catkin 02-28-2012 11:16 AM

Try reading the stat man page and running stat --format=%s on some file to see what that does.

Read this to see what $( ... ) does.

Read the find man page's entry on -print0 to see how that makes find's output be a list of filenames separated by the ASCII NUL character and read this for more on what the NUL character is/does.

In IFS= read -r -d '' file, the IFS= sets IFS to an empty string during execution of the following read. This seldom-used bash feature is briefly described here where it says "Otherwise, the variables are added to the environment of the executed command and do not affect the current shell environment". The effect of this on read is described later in this post.

Use help read at a command prompt (or the bash man page) for information on the read options.

The -r option prevents any "escape sequences" in the file name being processed -- so the characters in the find output are read exactly as find wrote them.

The -d option sets the delimiter that read uses to break the input. By default, it is line end so read processes each line until there are no lines left. Setting the delimiter to the empty string actually sets it to the NUL character (internally values in bash variables are terminated with a NUL character -- this is standard for strings in the C programming language), so read will return each time it gets a file name from find (remember the -print0 is making find separate file names with a NUL?).

read puts each file name into the variable "file". Normally it strips off any characters in IFS from the beginning and end of its input pieces. IFS is normally set to space, tab and line end so you don't want that in case there are file names that have any of those characters at beginning or end of their names. Setting IFS to the empty string means you get the file name exactly as find outputted it.

SharpyWarpy 02-29-2012 09:32 PM

Wow. I'm gonna be studying this thread for a LONG time. Thanks to the OP and catkin.

All times are GMT -5. The time now is 10:51 AM.