[Solved] Escape Quotes and Back Slash in Process Command Arguments

I wanted to run find . -type f -exec gcp --backup=numbered "{}" tmp \; in one instance of command.
I used \ to espace \ and ". Did I do it wrong?
I wrote:

let find_command = Command::new("find")
      .args( &[".", "-type", "f","-exec","gcp","--backup=numbered","\"{}\"","tmp","\\;"])

It complied but has error while executing the command. The error is about ; not found. I also break it down into serval arguments such as


Then it shown a different error about backslash.

Edit 1: Something I forgot to mention. I also printed the args along as &[".", "-type", "f","-exec","gcp","--backup=numbered","\"{}\"","tmp","\\;"] with the formatter {:#?}. It shows the escape character. I don't now if the formatter chose to print it or I didn't escape it properly.

How can I fix this?

Thank you for replying in advance.

Both quotes and backslash in "{}" and \; are not part of the argument but served as escaping in Bash.
The correct way to write is following:
.args( &[".", "-type", "f","-exec","gcp","--backup=numbered","{}","tmp",";"])

Please edit your post to properly format your code.

My guess is that the semicolon is removed by bash when you execute it in the terminal, so find isn't actually given a semicolon argument. Note also that you left the quotes in "{}". Bash likely removed those before giving them to find.

1 Like

Thank you, post syntax fixed.
Your reply is really helpful. Problem is also solved. I just realized both quotes and backslash in "{}" and \;are not part of the argument but served as escaping in Bash.
I modified as following and it works as I expected:

 .args( &[".", "-type", "f","-exec","gcp","--backup=numbered","{}",result_path.as_path().to_str().unwrap(),";"])
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.