0

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:

variable=$(command)
variable=`command`

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
done

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

closed as off-topic by Gilles, Archemar, Networker, sam, dhag Jul 21 '16 at 15:30

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions describing a problem that can't be reproduced and seemingly went away on its own (or went away when a typo was fixed) are off-topic as they are unlikely to help future readers." – Gilles, Archemar, Networker, sam, dhag
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 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
1

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"
done

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 – steeldriver 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... – don_crissti Jul 6 '16 at 16:26

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