LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   Bash: Problem with Escaping the Space Character (https://www.linuxquestions.org/questions/linux-software-2/bash-problem-with-escaping-the-space-character-4175584013/)

ghborrmann 07-07-2016 11:27 AM

Bash: Problem with Escaping the Space Character
 
In a bash script, I have the command:
Code:

ls -l --time-style=+'%y/%m/%d %H:%M:%S'
which works perfectly. I have tried to put all the options into a bash variable, but can't get ls to work that way:
Code:

options="-l --time-style=+'%y/%m/%d %H:%M:%S'"
ls $options
ls: cannot access '%H:%M:%S': No such file or directory

I have tried escaping the space character, with no effect. How can I get this to work?

hydrurga 07-07-2016 12:21 PM

Try this:

Code:

options=(-l --time-style=+'%y/%m/%d %H:%M:%S')
ls "${options[@]}"

Don't ask why it works - I don't know. :) I was just intrigued by your question, found the following thread, and played around a little with the arrays option:

http://unix.stackexchange.com/questi...ial-characters

Hopefully, someone else will elucidate...

ghborrmann 07-07-2016 12:37 PM

Works like a charm! Thanks!

john2 07-07-2016 12:39 PM

I was intrigued too. The only way I could find is to use eval:
Code:

options="-l --time-style=+'%y/%m/%d %H:%M:%S'"
eval "ls" $options

hydrurga's way looks neater though :). It probably works by avoiding double quotes - backslash within double quotes only works as escape character when followed by ‘$’, ‘`’, ‘"’, ‘\’, or newline. See here:https://www.gnu.org/software/bash/ma...le-Quotes.html

Edit: The quotes around ls are optional.

hydrurga 07-07-2016 12:40 PM

Quote:

Originally Posted by ghborrmann (Post 5571986)
Works like a charm! Thanks!

Nice. That page I linked to makes very interesting reading too.

Can you mark this thread as "Solved" please? Cheers.

keefaz 07-07-2016 05:58 PM

Another way is to alias ls, like
Code:

alias lstime='ls -l --time-style=+"%y/%m/%d %H:%M:%S"'


All times are GMT -5. The time now is 07:25 PM.