1

I am trying to add a variable on my script like this:

ssh root@$dev 'cat /etc/hosts > /var/tmp/hosts_$dev_$(date +%F)'

But, this does not work, I tried with

/var/tmp/hosts\_$dev\_$(date +%F)'
/var/tmp/hosts_${dev}_$(date +%F)'

Can someone please help me the output will still be no matter what I do.

hosts_2017-06-20

Resolution for future use:

I used single quotes instead of double quotes like this:

ssh root@$dev "cat /etc/hosts > /var/tmp/hosts\_$dev\_$(date +%F)"
6
  • your problem is the variable dev is not defined. Commented Jun 28, 2017 at 10:36
  • it is defined that ssh is inside a for loop that reads the IP address from a file Commented Jun 28, 2017 at 10:38
  • 1
    No; You problem is that you are using SINGLE QUOTES, and this will preserve the literal value of that sentence, not the content of $dev. Try to use double quotes instead - stackoverflow.com/questions/6697753/… Commented Jun 28, 2017 at 10:39
  • Also exec ssh on this way: ssh -o dev=$dev Commented Jun 28, 2017 at 10:40
  • @nwilder Yes! that was it.... the single quotes. Commented Jun 28, 2017 at 10:43

1 Answer 1

3

Let me quote this wonderful question with it's selected answer, to avoid explaining again something that was already answered on other site of stackexchange. This is the section of bash(1) manpage related to variable quoting:

3.1.2.2 Single Quotes

Enclosing characters in single quotes (') preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.

3.1.2.3 Double Quotes

Enclosing characters in double quotes (") preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !. The characters $ and ` retain their special meaning within double quotes (see Shell Expansions). The backslash retains its special meaning only when followed by one of the following characters: $, `, ", \, or newline. Within double quotes, backslashes that are followed by one of these characters are removed. Backslashes preceding characters without a special meaning are left unmodified. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an ! appearing in double quotes is escaped using a backslash. The backslash preceding the ! is not removed.

The special parameters * and @ have special meaning when in double quotes (see Shell Parameter Expansion).

Answer: That is why on your destination file you had $dev instead of the contents of that variable.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.