1

I want to use sed with a variable. My script:

input_variable="test" &&
ssh root@192.168.7.2 'cd /path/to/file && sed -i "s/this is not/this is a $input_variable/g" text.txt'

My script is supposed to change this is not into this is a test

However it changes it to this is a and somehow ingnoring the variable input_variable

Anyone an idea?

Tom
  • 2,545
  • 5
  • 31
  • 71
  • 2
    It's ignoring it because the command you're giving to `ssh` is in single quotes, so `bash` isn't interpolating variables into it. The shell that executes the command on the remote machine *is* interpolating variables being the `sed` script on the command line is in double quotes, but the variable is set on the local machine, not remote. Read the `bash` manual page section about variable interpolation. – blm Jan 08 '16 at 18:52
  • 1
    Your outer single quotes prevent the shell from interpreting `$input_variable`. Try: `ssh root@192.168.7.2 "cd /path/to/file && sed -i \"s/this is not/this is a $input_variable/g\" text.txt"` – lurker Jan 08 '16 at 18:53
  • @lurker works, thanks! – Tom Jan 08 '16 at 19:02

2 Answers2

1

Environment variables will not be replace in single quoted strings. Did you try:

input_variable="test" &&
ssh root@192.168.7.2 "cd /path/to/file && sed -i \"s/this is not/this is a ${input_variable}/g\" text.txt"
George Houpis
  • 1,729
  • 1
  • 9
  • 5
1

You're not interpolating that variable because you are using single quotes. I recommend continuing to use single quotes except for around the variable where you should switch to double quotes:

input_variable="test" &&
ssh root@192.168.7.2 'cd /path/to/file && sed -i "s/this is not/this is a '"$input_variable"'/g" text.txt'
Paul
  • 139,544
  • 27
  • 275
  • 264