1
paste0(" SqlCmd -s sqlserver2 -Q ", "\"BACKUP DATABASE [mydb] TO DISK = '","D:/temp/mydbcopy.bak' ") 

is giving output as

" SqlCmd -s sqlserver2 -Q \"BACKUP DATABASE [mydb] TO DISK = 'D:/temp/mydbcopy.bak' "

but I want the output to be without the backslash

" SqlCmd -s sqlserver2 -Q "BACKUP DATABASE [mydb] TO DISK = 'D:/temp/mydbcopy.bak' " "

Please help.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
bob
  • 71
  • 1
  • 1
  • 6
  • A single backslash is a escape character in CRAN. Try replacing it with double backslash? https://stackoverflow.com/questions/11806501/how-to-escape-backslashes-in-r-string – Adam Quek Aug 16 '19 at 08:27
  • Thanks, Adam. I tried but it shows the syntax error – bob Aug 16 '19 at 08:30

1 Answers1

1

Your code does the correct thing.

The backslash isn’t actually in the string, just as the surrounding quotes aren’t in the string. That’s just how R displays character strings in the terminal. To see the actual string content, use message:

x = paste0(" SqlCmd -s sqlserver2 -Q ", "\"BACKUP DATABASE [mydb] TO DISK = '","D:/temp/mydbcopy.bak' ") 
message(x)

This also shows you that your string is (probably) currently missing a closing " character.

As a general rule I strongly recommend against building command lines using raw string functions, it’s error-prone and hard to read. Use shQuote instead: this function is purpose-built to ensure correctly quoted arguments.

cmd_tokens = c("SqlCmd", "-s", "sqlserver2", "-Q", "BACKUP DATABASE [mydb] TO DISK = 'D:/temp/mydbcopy.bak'")
cmd = paste(shQuote(cmd_tokens), collapse = " ")

Here, each token of the command line (the command itself and all the arguments) are individual strings in a vector, and we apply shQuote to all of them in turn before concatenating them. Better yet, instead of concatenating the command yourself, pass the tokens as they are to the system2 command to execute it:

args = c("-s", "sqlserver2", "-Q", "BACKUP DATABASE [mydb] TO DISK = 'D:/temp/mydbcopy.bak'")

system2("SqlCmd", args)
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • Thanks, Konrad. I wasted so much time thinking why the backslash is getting shown, but you're right when I do print the output of paste0 I get correct results. I fixed the ending " issue. Thanks a lot for helping and providing info about shQuote, I'll try to follow your advice. – bob Aug 16 '19 at 08:48