ls command different output in shell script -

Most popular tags

Welcome to, where you can ask questions and receive answers from other members of the community.

ls command different output in shell script

I have a strange behavior on my linux box and i want your advice. I want to capture the output of this command

ls -log /some/directory 

Running command from command line the result is OK:

-rw-r--r--. 1 22650880 2013-09-09 12:02 file1.txt
-rwxr--r--. 1 20733952 2012-07-09 17:42 file2.txt
-rw-r--r--. 1 31596544 2013-09-09 23:42 file3.txt
-rw-r--r--. 1 15773696 2013-09-10 11:15 file4.txt

so my final result using awk ( ls -log /some/directory| awk '{print $6","$4" "$5}' | tr "\n" ";" ):

file1.txt,2013-09-09 12:02;file2.txt,2012-07-09 17:42;... 

My problem appear when I put ls command in a Bash script, because the date is converted. Instead of 2013-09-10 11:15 the result is Sep 09 12:02

How can i get the date like in command line output?

1 Answer

The output of ls depends on the LANG environment. From info ls:

By default, file timestamps are listed in abbreviated form. Most locales use a timestamp like 2002-03-30 23:45'. However, the default POSIX locale uses a date likeMar 30 2002' for non-recent timestamps, and a date-without-year and time like `Mar 30 23:45' for recent timestamps.

Compare these two variants:

$ LANG=C ls -log
total 0
-rw-r--r--  1 0 Sep 10 10:34 file1
-rw-r--r--  1 0 Sep 10 10:34 file2
-rw-r--r--  1 0 Sep 10 10:34 file3
-rw-r--r--  1 0 Sep 10 10:34 file4

$ LANG=en_US.utf8 ls -log
total 0
-rw-r--r--  1 0 2013-09-10 10:34 file1
-rw-r--r--  1 0 2013-09-10 10:34 file2
-rw-r--r--  1 0 2013-09-10 10:34 file3
-rw-r--r--  1 0 2013-09-10 10:34 file4

But, as always, it is a bad idea to parse the output of ls, because -- as you have seen -- breaks easily. Consider to use stat instead

for file in *; do
    stat -c "%n,%z;" "$file"

where you can specify which timestamp you want more precisely:

%x     Time of last access
%y     Time of last modification
%z     Time of last change

And you don't need awk anymore, too.

You can specify a date-format with your ls command:

ls -log --time-style="long-iso" /some/directory 

This always results in the same date format of YYYY-MM-DD.