I'm trying to assign the output of a grep command to a variable in a bash script and the variable comes up empty. When I run the following:

el_value=$(grep '<$2>.*<$2>' $1 | sed -e 's/^.*<$2/<$2/' | cut -f2 -d'>'| cut -f1 -d':')
echo "DEBUG: The value of el_value is '$el_value'"

The output is:

DEBUG: The value of el_value is ''

If I run the grep command outside of the script (and substitute the variables for real values) I get the output I'm expecting.

Here is a snippet of script. Use this script and add the values listed above.


if [ $# -ne 3 ]; then
echo 1>&2 'This script replaces xml element’s value with the one provided as a command parameter \n\n\tUsage: $0 <xml filename> <element name> <new value>'
exit 127

el_value=`grep "<$2>.*<$2>" $1 | sed -e "s/^.*<$2/<$2/" | cut -f2 -d'>'| cut -f1 -d':'`
echo "DEBUG: The value of el_value is '$el_value'"
  • Something happened when I posted the command. It's actually: – user34769 Mar 22 '13 at 17:37
  • el_value=$(grep '<$2>.*<$2>' $1 | sed -e 's/^.*<$2/<$2/' | cut -f2 -d'>'| cut -f1 -d':') – user34769 Mar 22 '13 at 17:39


el_value=$(sed -n "s/.*<$2>\([^:<]*\).*/\1/p" < "$1")

In your code the problems were:

  • single quotes around $2 which meant it wasn't expanded
  • missing / to search for the closing tag in the grep command.

I think it's a quote issue. Inside your grep & sed argument, $1 and $2 are not parsed because of your simple quotes ('). Try this one :

el_value=$(grep "<$2>.*<$2>" $1 | sed -e "s/^.*<$2/<$2/" | cut -f2 -d'>'| cut -f1 -d':')
  • Thanks for the reply, but I still get the same results. – user34769 Mar 22 '13 at 17:48
  • Please post some content for testing. – GHugo Mar 22 '13 at 17:59
  • Create a file called file.xml. Add this line to the file: <p4Port>server1:1986</p4Port>. Then pass in the values file.xml server1 server2 – user34769 Mar 22 '13 at 18:13
  • I think you want to do this : el_value=$(grep "<$2>.*</$2>" $1 | sed -e "s/^.*<$2/<$2/" | cut -f2 -d'>'| cut -f1 -d':'). And call it with file.xml p4Port server1. Remember that xml langage is not a regular langage, so you might find case wich your sed exp will not work. Use a xml parser and a script langage like python/ruby/perl/other – GHugo Mar 22 '13 at 18:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.