-1

I'm writing a bash script which contains a variable called "line", and I want to print it's content. The problem is that the "line" variable is a string which contains the '$' char.

My question is how can I print the value of the "line" variable, without replacing the dollars with variables.

For example, if "line" is containing "a$#gz%^", this code:

 echo $line

Will output this:

a0gz%^

And if I'll put the '$line' in single quotes, it will just print '$line':

 echo '$line'

$line

Hope you'll be able to help.

Or Nevo
  • 175
  • 1
  • 10
  • 1
    I can't reproduce the problem. `line='a$#gz%^'; echo $line` in bash prints `a$#gz%^`. The problem is likely that `line` actually contains `a0gz%^`, and that expansion of `$#` occurred when you set the `line` variable. – Ross Ridge Dec 08 '15 at 07:31
  • 1
    Q: How do I assign a value that has "$" to a bash variable? A: Easy: use single quotes: `line='a$#gz%'`. Q: How do I print that variable? A: Easy: just `echo $line`. – paulsm4 Dec 08 '15 at 07:36
  • 2
    ^^ I would recommend `echo "$line"`... – anishsane Dec 08 '15 at 07:39

2 Answers2

1

You have to quote the string when you assign it to the variable:

line='a$#gz%^'

Otherwise, $# is expanded before the assignment.

To output the literal variable, use double quotes

echo "$line"

It looks confusing at first, but it is actually pretty simple (at least to a first approximation):

  • string with $line in it -- never what you want, particularly if it includes a variable. OK if there is no variable and the string is just letters and numbers (and pattern characters if you want them to be expanded). Expands variables, splits into words, expands filename patterns.
  • "string with $line in it" -- expands variables, but doesn't word split or expand filename patterns
  • 'string with $line in it' -- literal string, just the characters between the apostrophes
rici
  • 234,347
  • 28
  • 237
  • 341
  • The problem is that the line variable is assigned with a loop over file lines: while read line;do ... done < $fileName – Or Nevo Dec 08 '15 at 07:31
  • 2
    @OrNevo: The `$#` in the variable will not be expanded by any form of variable insertion. If you have a clearer example, *edit your question*. Do not put important information in comments. – rici Dec 08 '15 at 07:33
  • 1
    @ornevo: that `while read` loop will *not* trigger what you claim to see -- *unless* the input is coming from a here-doc. In that case, the `$#` will be expanded in the here-doc unless you quote the end marker (`<<'END'`) – rici Dec 08 '15 at 08:00
0

You can store string in variable having special characters by giving escape sequence like below -

line="a\$#gz%^"

And then echo $line

Murli
  • 1,258
  • 9
  • 20