jcalton88 jcalton88 - 7 months ago 37
Bash Question

How to quote a variable in bash script

I have a command I need to run in a bash script that takes the output of a previous command and inserts it into a new command.

So for example:

VARIABLE=$(cat "file.txt" | grep "text")

Then use that variable in another command:

mycommand -p "$VARIABLE"

The catch is the $VARIABLE will always contain special characters, namely $ and / which I need so I need to single quote that so the special characters are taken literal.

I've tried
which didn't work.

What I'm trying to accomplish is I need to grab a line out of a text file that includes my search term, which is unique and only one line will have it.

I then need to input that line (well, half of it, I'm also cutting the line and using the second half) into another command. I am able to successfully grab the text I need which I verified by echoing the variable afterwards. The problem is the variable contains $ and \ that are being interpreted as special characters.

For example:

my command -p $345$randomtext\.moretext

Without single quoting the variable it is interpreted which throws errors.


If should work as you have written it here (assuming that I'm parsing the garbled formatting correctly):

VARIABLE=`cat "file.txt" | grep "text"`
mycommand -p "$VARIABLE"

If there are problems handling special characters in the search results (other than null, which cannot be stored in a shell variable), then they're almost certainly due to mishandling in mycommand, not in how it's being called. Here's an example:

$ cat file.txt 
There are some $special \characters\\\\ in this text file.
This is another line of text.
$text $VARIABLE $HOME etc.
$ VARIABLE=`cat "file.txt" | grep "text"`
$ printargs -p "$VARIABLE"
Got 2 arguments:
    'There are some $special \\characters\\\\\\\\ in this text file.\nThis is another line of text.\n$text $VARIABLE $HOME etc.'

printargs is a simple python program that prints a pythonic representation of its arguments (note that it doubled all of the backslashes, and printed the line breaks as '\n', because that's how you'd write them in a python string):


import sys

print "Got", len(sys.argv)-1, "arguments:"
for arg in sys.argv[1:]:
    print "    " + repr(arg)

BTW, I have a couple of stylistic suggestions: use lowercase names for shell variables to avoid conflicts with environment variables that have special meanings (e.g. assigning to $PATH will lead to trouble). Also, cat file | grep pattern is a useless use of cat; just use grep pattern file.