Escaping characters

I want to execute this command

ls -pt | grep -v / | tr '\n' ',' | sed "s/,$//g"

by executeCommandline.
As i am not the expert for escaping characters I end up with this helper variable:

var cmdOptions = "-pt" +  " | " +  "grep -v /" + " | " +  "tr \'\\n\' \',\'" +  " | " +  "sed \'s/,$//g\'"

logInfo shows that this is ok so far.
However,

val arrFilenames = executeCommandLine(Duration.ofSeconds(2),"ls",cmdOptions)

throws the following error:

ls: cannot access '"-pt | grep -v / | tr '\''\n'\'' '\'','\'' | sed '\''s/,$//g'\''"': No such file or directory

Where is my error?

executeCommandLine doesn’t give you a shell (sh, bash, csh, etc). It just executes the one command. Therefore operations provided by the shell like |, >, etc. are not available to you. Because of that, it’s literally telling ls to look for the file "-pt | grep -v / | tr '\''\n'\'' '\'','\'' | sed '\''s/,$//g'\''" which obviously doesn’t exist.

Your problem isn’t escaping, it’s that there’s not | operator.

You will either need to put this into a script that OH calls, or construct the command to pass this to a shell to execute.

2 Likes