Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I hope someone can help me here. 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.


Sorry, I guess you need a little more information than that. Here is a snippet of script. Use this script and add the values listed above.

#!/bin/bash

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
fi

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'"
share|improve this question
    
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

2 Answers 2

Try:

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.
share|improve this answer

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':')
share|improve this answer
    
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

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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