Search code examples
linuxshellsshsedremote-server

How to run sed on remote server using ssh inside a shell script(variables included)


I have a situation here, I am trying to run a sed command on a remote shell inside my shell script and using variables that are dynamic and end up getting the same error again and again.

This is the sed command that is running fine on local shell without any error. I have used this regular expression after thorough testing and trust me there is no problem with it.

sed -i 's/  #0\t30718/ 0\t30718/' ./config.txt

Trying to run this in a remote shell using ssh:

ssh root@sys_name sed -i 's/  #0\t30718/ 0\t30718/' /absolute-path/vconfig.txt

And when I try to run this command using variables. (30718 and path of the file are the variables):

ssh root@sys_name 'sed -i "s/0\t${pe_list[0]}/#0\t${pe_list[0]}/g" $file_path'

or like this:

ssh root@sys_name "sed -i 's/0\t${pe_list[0]}/#0\t${pe_list[0]}/g' $file_path"

I either get the sed: -e expression #1, char 2: unterminated `s' command error or the sed command executes with undesired output matching the variable names as is. Basically, put in few words, I want to execute a sed command on a remote shell using ssh, and the constraint is that the entire command is part of a script and the values to be matched and the filename are variables in that file.


Solution

  • You have variable set in your local shell, but is is not sed variable, so you should exit sed environment by closing it with single quote, put your variable, then open again with single quote and continue sed stuff:

    sed -e 's/Red Hat/'${z}'/' /etc/redhat-release
    

    In case your $z variable contains spaces, you need to embrace it with double quotes:

    sed -e 's/Red Hat/'"${z}"'/' /etc/redhat-release
    

    Finally, when you sending your command through ssh you are also adding double quotes around whole command, so all double quotes used in this command should be escaped, else everything between these will be evaluated locally on your source host. So do like this:

    z="BLACK HAT"    
    ssh root@sys_name "sed -e 's/Red Hat/'\"${z}\"'/' /etc/redhat-release"
    

    You will get:

    BLACK HAT Enterprise Linux Server release 6.10 (Santiago)