views:

70

answers:

4

If I have a variable containing an unescaped dollar sign, is there any way I can echo the entire contents of the variable?

For example something calls a script:

./script.sh "test1$test2"

and then if I want to use the parameter it gets "truncated" like so:

echo ${1}
test1

Of course single-quoting the varaible name doesn't help. I can't figure out how to quote it so that I can at least escape the dollar sign myself once the script recieves the parameter.

+2  A: 

The variable is replaced before the script is run.

./script.sh 'test1$test2'
Ignacio Vazquez-Abrams
Yes, this seems to be the case :)
Not22
There are other situations though where I actually have variables with unescaped dollar signs, like when I'm reading data from files. I then want to call my script with this data, so is it my only option to sed the entire file before reading it?
Not22
Reading data from files does not do variable substitution.
Ignacio Vazquez-Abrams
+2  A: 

The problem is that script receives "test1" in the first place and it cannot possibly know that there was a reference to an empty (undeclared) variable. You have to escape the $ before passing it to the script, like this:

./script.sh "test1\$test2"

Or use single quotes ' like this:

./script.sh 'test1$test2'

In which case bash will not expand variables from that parameter string.

Vlad Lazarenko
A: 

As Ignacio told you, the variable is replaced, so your scripts gets ./script.sh test1 as values for $0 and $1.

But even in the case you had used literal quotes to pass the argument, you shoudl always quote "$1" in your echo "${1}". This is a good practice.

Benoit
And the braces are *not* needed, since this is a simple substitution.
Ignacio Vazquez-Abrams
yes they are not needed. Using them is just optional.
Benoit
A: 

by using single quotes , meta characters like $ will retain its literal value. If double quotes are used, variable names will get interpolated.

ghostdog74