Search code examples
linuxbashrhel7rhel6

Edit remote file with variables


I've write this script but it does not works:

E_OPT=" some_host(ro,insecure) some_host2(ro,insecure)"

echo -n "Insert path to export [ ex: /path/test ]"
read PATH

FINAL=$PATH$E_OPT

ssh SERVER echo "$FINAL" >> file
or
ssh SERVER echo '$FINAL >> file'
or
ssh SERVER 'echo "$FINAL" >> file'

How can I pass text in variable to append in remote files?


Solution

  • There are a couple of problems here. The first is with read PATH. The variable PATH is one of many that have special meaning to the system: it defines where to look for executables (e.g. for commands). As soon as you redefine it as something else, the system will be unable to find executables like ssh, so commands will start to fail. Solution: use lowercase or mixed-case variable names to avoid conflicts with any of the special-meaning variables (which are all uppercase).

    Second, all of your attempts at quoting are wrong. The command is going to go through two levels of shell parsing: first on the local computer (where you want the variable $FINAL -- or better $final -- to be expanded), and then on the remote server (where you want the parentheses to be in quotes, so they don't cause shell syntax errors). This means you need two levels of quoting: an outer leven that gets parsed & removed by the local shell, and a second level that gets parsed & removed by the remote shell. Variable expansion is only done in double-quotes, not single-quotes, so the outer level has to be double-quotes. The inner level could be either, but single-quotes are going to be easiest:

    ssh SERVER "echo '$final' >> file"
    

    Now, it may look like that $final variable is in single-quotes so it won't get expanded; but quotes don't nest! As far as the local shell is concerned, that's a double-quoted string that happens to contain some single-quotes or apostrophes or something that doesn't really matter. When the remote shell receives the command, the variable has been substituted and the outer quotes removed, so it looks like this:

    echo '/some/path some_host(ro,insecure) some_host2(ro,insecure)' >> file
    

    ...which is what you want.