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")
mycommand -p "$VARIABLE"
my command -p $345$randomtext\.moretext
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: '-p' '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):
#!/usr/bin/python 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.