0

I don't know how to print a variable inside a string of a string.

I first started off without a variable like this and it worked perfectly:

#!/bin/bash

ssh 1.1.1.1 $'sudo -H -u apache bash -c 'cd ~/html; echo development > stuff.text''

When I login to my server at 1.1.1.1, I can see that the file stuff.text has the word development. Perfect.

Then I made this bash script:

#!/bin/bash

BRANCH=development ssh 1.1.1.1 $'sudo -H -u apache bash -c 'cd ~/html; echo ${BRANCH} > stuff.text''

But running this bash script causes an empty stuff.text file. I also tried each of these commands, but they all gave syntax/parse errors:

ssh 1.1.1.1 $`sudo -H -u apache bash -c 'cd ~/html; echo ${BRANCH} > stuff.text'`
ssh 1.1.1.1 ${`sudo -H -u apache bash -c 'cd ~/html; echo ${BRANCH} > stuff.text'`}
ssh 1.1.1.1 ${sudo -H -u apache bash -c 'cd ~/html; echo ${BRANCH} > stuff.text'}
ssh 1.1.1.1 ${"sudo -H -u apache bash -c 'cd ~/html; echo ${BRANCH} > stuff.text'"}

How do I write a variable inside the string of another string?

  • The notation you are using doesn't make sense. What exactly are you saying that your first command did? What do you think this is doing: ssh 1.1.1.1 $'sudo -H -u apache bash -c \'cd ~/html; echo development > stuff.text\''? You cannot escape single quotes, this is just a very complex notation to do something actually quite simple. Please [edit] your question and explain what you are trying to do. – terdon May 13 '21 at 12:42
  • 1
    @terdon, you can't escape single quotes within plain '...', but you can within a $'...'. Of course the syntax highlighting doesn't know it here. – ilkkachu May 13 '21 at 12:53
  • @ilkkachu thanks! I had never seen a shell context that allowed escaping single quotes like that before. Of course, the OP has no reason to use $'...' at all, but that's a different issue. – terdon May 13 '21 at 12:59
  • Instead of just throwing a bunch of syntax at the wall, I'd encourage you to read about bash quoting: 3.1.2 Quoting – glenn jackman May 13 '21 at 13:17

2 Answers2

0

After a bunch of trial an error, I found that this worked:

#!/bin/bash

BRANCH=development ssh 1.1.1.1 $"sudo -H -u apache bash -c 'cd ~/html; echo ${BRANCH} > stuff.text'"

Now i can see the word development in the file ~/html/stuff.text

0

You are using a needlessly complicated notation. The $ isn't needed at all here, ssh takes a string that is executed as a command on the remote server. You also don't need to cd anywhere. Try this:

#!/bin/bash

avoid CAPS for shell variable names.

branch=development

ssh 1.1.1.1 "sudo -H -u apache bash -c 'echo $branch > ~/html/stuff.text'"

terdon
  • 242,166