Right now I am using ls -lt /my/directory (see below) then php parses the output. But inconsistently because the delimiter is space and there might be two or more spaces in between two fields.

The solution is output only file name and its size. How can I list files (using wild card) and its full size in command line?

So instead of

-rw------- 1 db2inst1 db2iadm1 855658496 Apr 22 02:31 MONTE.0.db2inst1.NODE0000.CATN0000.20120422023005.001

I get

855658496 MONTE.0.db2inst1.NODE0000.CATN0000.20120422023005.001
  • 6
    Don't parse ls output, ever. Instead, you should be asking how to get the information you want directly with PHP in a more robust fashion, perhaps on StackOverflow? – jw013 May 3 '12 at 6:38
  • I do ls on remote server over ssh so I cannot do it directly in PHP. – Radek May 3 '12 at 6:45
  • If you can, mount the remote directory over sshfs and forget about parsing ls or stat output. – Gilles 'SO- stop being evil' May 3 '12 at 23:26

As others have noted, if this is a dynamic web application, you're much better off using PHP's functions for accessing file size.

But if you're going to get it by executing a shell command, don't use ls. Instead, use stat, and tell it exactly what you want:

$ stat -c '%n %s' x.txt
x.txt 12
  • 1
    The -t used in the original ls call can hardly be reproduced this way. – manatwork May 3 '12 at 6:50
  • 1
    The full command I am going to use is ssh root@monte stat -c \'%n %s\' /var/lib/edumate/backup/*MONTE* . Thank you. – Radek May 3 '12 at 6:50
  • @manatwor: thank you for pointing that out. Need to so some sorting in php then. – Radek May 3 '12 at 6:51
  • 1
    @Radek, then you would probably like to add %Y (time of last modification, seconds since Epoch) too to the format string. – manatwork May 3 '12 at 6:53
  • 1
    On OS X (and probably other BSDs) stat takes different options. The equivalent to the command in the answer would be: stat -f '%N %z' x.txt. – Ionoclast Brigham Jul 17 '15 at 22:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.