Home > Mobile >  How to escape double quotes when using Rscript function in Bash
How to escape double quotes when using Rscript function in Bash

Time:09-28

How can I escape double quotes to run this code block on the command line? The part of the code that is problematic is paste('! LaTeX Error: File', paste0("`", x, "'.sty'"), 'not found.')).

Rscript \
  -e "biosketch_pkgs <- list('microtype', 'tabu', 'ulem', 'enumitem', 'titlesec')" \
  -e "lapply(biosketch_pkgs, function (x) {tinytex::parse_install(text=paste('! LaTeX Error: File', paste0("`", x, "'.sty'"), 'not found.'))})"

I have tried to escape the double quote using the below but it returns unexpected EOF while looking for matching ''`

Rscript \
  -e "biosketch_pkgs <- list('microtype', 'tabu', 'ulem', 'enumitem', 'titlesec')" \
  -e "lapply(biosketch_pkgs, function (x) {tinytex::parse_install(text=paste('! LaTeX Error: File', paste0("\`"\, x, "\'.sty'"\), 'not found.'))})"

CodePudding user response:

Instead of worrying about how to escape specific strings, think about handling in them a way that avoids the need to do any escaping at all. Running Rscript - tells Rscript to read the source code to run on stdin, while <<'EOF' makes all content up to the next line containing only EOF be fed on stdin. (You can replace the characters EOF with any other sigil you choose, but it's important that this sigil be quoted or escaped to instruct the shell not to modify the content in any way).

Rscript - <<'EOF'
  biosketch_pkgs <- list('microtype', 'tabu', 'ulem', 'enumitem', 'titlesec')
  lapply(biosketch_pkgs, function (x) {
    tinytex::parse_install(text=paste('! LaTeX Error: File',
                                      paste0("`", x, "'.sty'"),
                                      'not found.'))
  })
EOF

If you did have a compelling reason to use Rscript -e, though, a correct escaping would put backslashes before backticks, double quotes, or other syntax that has meaning to the shell within a double-quoted string, as follows:

Rscript \
  -e "biosketch_pkgs <- list('microtype', 'tabu', 'ulem', 'enumitem', 'titlesec')" \
  -e "lapply(biosketch_pkgs, function (x) {tinytex::parse_install(text=paste('! LaTeX Error: File', paste0(\"\`\", x, \"'.sty'\"), 'not found.'))})"
  • Related