How should I escape '&&' and other special characters when running a bash command with read() or run()?

Viewed 417

My code:

df = read(`df -h|grep /dev/sda1 && df -h|grep pCloud`, String)

When I run it I get the following message from Julia:

Warning: special characters "#{}()[]<>|&*?~;" should now be quoted in commands
 │   caller = #shell_parse#333(::String, ::Function, ::String, ::Bool) at shell.jl:100
 └ @ Base ./shell.jl:100
df: invalid option -- '|'
Try 'df --help' for more information.
ERROR: LoadError: failed
process: Process(`df '-h|grep' /dev/sda1 '&&' df '-h|grep' pCloud`, ProcessExited(1)) [1]

I have found someone having a similar problem, but they seem to have resolved this issue without escaping.

1 Answers

Julia commands are not run in a shell, so using shell features like that will not work. If you want to pipe from one command to another, you should use the pipeline function and if you want to test the success or failure of a command or pipeline, run it with the success function. In this case, you could do this:

success(pipeline(`df -h`, `grep /dev/sda1`)) &&
success(pipeline(`df -h`, `grep pCloud `))

Of course, in that case you could call df -h a single time and do

df = read(`df -h`, String)
contains(df, "/dev/sda1") && contains(df, "pCloud")
Related