1

For a given file one may issue the bash command:

ls -la --full-time --time-style long-iso --time-style=+"%Y-%m-%d %H:%M:%S" file

This works of course.

I have a larger script in which I would like to define the time-style and to reference it multiple times:

TMP_TIME_STYLE="--full-time --time-style long-iso --time-style=+""%Y-%m-%d %H:%M:%S"""

Executing the command

ls -la ${TMP_TIME_STYLE} file

results in the error message:

ls: accessing '%Y-%m-%d' is not possible: no such file or directory.

It seems that not all the options in ${TMP_TIME_STYLE} are passed to ls.

I already tried to put additional "" just in front of %Y-%m-%d and immediately behind %H:%M:%S, however the same error message.

How to safely pass the contents of ${TMP_TIME_STYLE} to ls?

pLumo
  • 22,565
DieterH
  • 31
  • 3
  • You can use an array for the options, as indicated in the duplicate. But for your use-case I'd go with an alias. e.g. alias lst='ls -la --full-time --time-style long-iso --time-style=+"%Y-%m-%d %H:%M:%S"'. Then lst file. – pLumo Nov 26 '21 at 09:27
  • note that you don't even have quotes in the value of TMP_TIME_STYLE: in TMP_TIME_STYLE="... --time-style=+""%Y-%m-..., the second and third quotes just close and reopen the quoted string, the result would be the same with TMP_TIME_STYLE="...--time-style=+%Y-%m-%d %H:%M:%S". Regardless, the quotes wouldn't help, this is what everyone tries and what is explained in the linked question. You could do TIME_STYLE="--time-style=+%Y-%m-%d %H:%M:%S" and ls -l ... "$TIME_STYLE" though, but you can't have the string split on one space but not another. – ilkkachu Nov 26 '21 at 09:30
  • @pLumo, though they mentioned a script, so in Bash they'd have to explicitly enable them too (shopt -s expand_aliases). A function might be better here though. – ilkkachu Nov 26 '21 at 09:34
  • I was not aware that aliases won't get expanded in scripts by default ... Good to know :-) – pLumo Nov 26 '21 at 09:36

0 Answers0