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?

5
  • Does this answer your question? $VAR vs ${VAR} and to quote or not to quote
    – roaima
    May 13 at 12:28
  • 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 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 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 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 May 13 at 13:17
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'"
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

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.