LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   replacing empty values in bash (https://www.linuxquestions.org/questions/linux-newbie-8/replacing-empty-values-in-bash-867945/)

xeon123 03-11-2011 10:01 AM

replacing empty values in bash
 
Hi,

I'm executing the below bash script, but when the m variable doesn't get any value it becomes empty. I don't want that.

Code:

for i in "$@"
do
    m=$(grep TOTAL_MAPS  $i | awk '{ print $2}');
    totalmaps+="<string>"$m"</string>"
done

Sometimes I get the string:
Code:

<string></string>
But I want in that cases return

Code:

<string>0</string>
how can i do that in bash?

szboardstretcher 03-11-2011 10:02 AM

Code:

m=0;
for i in "$@"
do
    m=$(grep TOTAL_MAPS  $i | awk '{ print $2}');
    totalmaps+="<string>"$m"</string>"
done


xeon123 03-11-2011 10:08 AM

I think that this don't work after the first iteration.
For example, I get the value 9 in the first iteration , and in the 2nd iteration it doesn't exist a value. In that case I'll get

Code:

<string>9</string>
<string></string>

which is wrong.

I think that the solution is to put an if clause, but the problem is that I don't know how can I check if the variable m has content or not.

xeon123 03-11-2011 10:23 AM

the solution is:

Code:

if [ "$m tr -d ' '" == "" ]

grail 03-11-2011 10:50 AM

Gees ... no need to reinvent the wheel. How about we just use bash builtins:
Code:

[[ $m ]] || m=0

ntubski 03-11-2011 11:05 AM

Quote:

Originally Posted by xeon123
Code:

if [ "$m tr -d ' '" == "" ]

This doesn't make sense, did you mean
Code:

if [ "$(echo $m | tr -d ' ')" == "" ]
Quote:

Originally Posted by grail
Gees ... no need to reinvent the wheel. How about we just use bash builtins:

There is a particular builtin just for this:
Code:

${m:=0}

grail 03-11-2011 11:12 AM

Quote:

There is a particular builtin just for this:
True enough and I thought about it, but based on what had been shown I thought he might get less lost with a test construct :)


All times are GMT -5. The time now is 04:22 AM.