Reputation: 11
I'm going nuts with this...let me explain...
I have a very simple Bash script with a function in it that receives 3 arguments. Those arguments are all strings. Everything was working fine 'til I had to pass a string with whitespaces to the function.
I also have some test code to call the function (whose name is substracFromFile):
# try the function
PATTERN=`echo -e '<Location test14>'`
echo "PATTERN IS $PATTERN"
HEADERPATTERN=`echo -e '<Location [a-zA-Z0-9]*>'`
echo "HEADERPATTERN IS $HEADERPATTERN"
FILE="subversion.conf"
echo "FILE IS $FICHERO"
substracFromFile $PATTERN $HEADERPATTERN $FILE
The output of this is:
PATTERN IS <Location prueba14>
HEADERPATTERN IS <Location [a-zA-Z0-9]*>
FILE IS subversion.conf
PATTERN ARGUMENT IS <Location
HEADERPATTERN ARGUMENT IS prueba14>
FILE ARGUMENT IS <Location
grep: <Location: No such file or directory
expr: syntax error
As you can see, when arguments are passed to the function and I echoed them to screen they are somehow splitted in the white space...let me show you the function initial code:
function substracFromFile
{
PATTERN=$1
HEADERPATTERN=$2
FILE=$3
# Debug only
echo "HEADER ARGUMENT IS $PATTERN"
# Debug only
echo "HEADERPATTERN ARGUMENT IS $HEADERPATTERN"
# Debug only
echo "FILE ARGUMENT IS $FILE"
This was working sweet as long as passed strings had no whitespaces at all. When I call the function strings seem to be ok, but I don't understand why they are splitted once the function is called....I'm sure this is something pretty dull, but I just don't get it...
Thanks in advance, Alex
Upvotes: 1
Views: 584
Reputation: 360035
Parts of your question are inconsistent with other parts. For example:
FILE="subversion.conf"
echo "FILE IS $FICHERO"
But I'm assuming those are just errors made while posting the question.
As ghostdog74 mentioned in a comment, you need to quote variables that contain whitespace. In particular, this line should have quotes around the variables:
substracFromFile "$PATTERN" "$HEADERPATTERN" "$FILE"
Also, I don't see why you're using echo
to set variables in lines such as this one:
PATTERN=`echo -e '<Location test14>'`
This could simply be:
PATTERN='<Location test14>'
If the value sometimes has escaped special characters in it, you can use one of these methods:
PATTERN=$'value\nwith\tescapes'
which would have "value" newline "with" tab "escapes" as its value.
Also, I recommend getting in the habit of not using all-caps for variable names. This will reduce the chance of name collisions with Bash's built-in variables.
Upvotes: 1