Search code examples
shellescapingshellexecute

shell script: single quote in execute


I'm having trouble using a single quote in a command executed from within a shell script. In my script I execute an rdesktop command that should have -u '' (<- 2 single quotes) as a parameter. However, no matter how I try to escape the quotes it is not passed correctly.

If I just echo $command the output is fine, if I execute it weird output is created

This is the part of the script that doesn't work:

command="rdesktop -u "\'\'" $server"
`$command`

I also tried executing it directly:

`rdesktop -u "\'\'" $server`

I would appreciate any help since I read quite a few tutorials on escaping characters in shell scripts and didn't find the solution..

EDIT:

interestingly enough, if I just use

command=rdesktop -u '' $server

and echo it, the output is fine however, if I execute it with

$command

it fails...


Solution

  • If your shell is bash or ksh or zsh, it's much safer and easier to build up a command with an array rather than a string:

    command=( rdesktop -u '' $server )
    

    and execute it like this

    "${command[@]}"
    

    I can't imagine the remote server needs to see a username named literally '' (i.e. 2 single quotes) -- it probably wants just an empty string.