I would like to put the output of a command into a variable. As far as I know, you have to use either of these:


The following should work from my point of view:

for i in $(ls -1); do
    modTime=$(/usr/gnu/bin/date -r $i +$F)
    echo $modTime

I tried backticks as well; nothing changes. If it is important, it's a bash shell.

  • 1
    Should be like that modTime='/usr/gnu/bin/date -r $i +%F' with backticks in place of quote
    – dubis
    Jul 6 '16 at 15:02

First, never parse the output of ls. The output is considered to be human readable, and not designed for parsing. It is much better to simply loop over the globbing, as I will show below.

The actual issue was that you used $F rather than %F. The former would have been an empty variable, and so it the date command would not have had any output. So, here is the modified command:

for i in ./*; do
    modTime="$(/usr/gnu/bin/date -r "$i" +%F)"
    echo "$modTime"

However, a single find command should do what you want:

find ./ -maxdepth 1 -printf "%TY-%Tm-%Td\n"
  • Even when using a shell glob, you need to quote the variable "$i" to stop the date command breaking on whitespace, I think Jul 6 '16 at 16:12
  • Technically, the globbing should escape spaces, etc., but you are correct that it is good practice to always quote strings, and even inside the other quotes. I'll update that.
    – DKing
    Jul 6 '16 at 16:15
  • 3
    No need to quote the RHS of variable assignment. So you don't need the outer quotes but (unless you're using zsh) you have to quote $i - that's parameter expansion, there's no such thing as globbing escaping spaces... Jul 6 '16 at 16:26

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