1

Having already learned much here, I'm back with a perplexing problem. I can run some string manipulation commands directly and get the expected results. When I put them in a function, the results are wonky.

Am I having brain cramp and missing the obvious? My code, with tests:

    get_name() { 
    # single-purpose function to build student name from FL
    # takes first word of string (first name) and moves to end
    # last name could be one or two words; 
    # first names including space will be mistreated, but for now, is best solution
    local string=$1 namefirst namelast name
    namefirst=${string%% *} # returns text up to specified char (" ")
    namelast=${string#$namefirst } # returns text minus specified string at start
    name=$namelast"_"$namefirst
    echo ${name// /_}
}


student="First Last1 Last2, Grade 1"
studentname=${student%%,*} # returns text up to specified char (,)
string=$studentname # save for standalone test

studentname=$(get_name $studentname)
echo "function studentname = $studentname"

echo "Now run same manips outside of function:"
namefirst=${string%% *} # returns text up to specified char (" ")
echo $namefirst
namelast=${string#$namefirst } # returns text minus specified string at start
echo $namelast
name=$namelast"_"$namefirst
echo ${name// /_}

The results:

function studentname = First_First
Now run same manips outside of function:
First
Last1 Last2
Last1_Last2_First

The last three lines show the expected string results. Why would the function's namelast fail (is set to namefirst)?

Many thanks for any input.

2
  • namelast=${string#$namefirst } .. Whatever is after the sign # is read as a comment.. You will have to put it differently to get the desired result Commented Feb 8, 2015 at 6:20
  • If this were the case, Vineeth, the tests as run after the function call would have returned the same result. In fact, # in string manipulation serves a special function. See e.g. the very useful tldp.org/LDP/abs/html/string-manipulation.html . Commented Feb 8, 2015 at 6:34

1 Answer 1

1

Problem is unquoted string here:

get_name $studentname

Since $studentname variable has value: First Last1 Last2

That has spaces in it therefore sending it without quotes is sending only the first word before space i.e. calling it as:

get_name "First"

Your function call should be:

get_name "$studentname"
Sign up to request clarification or add additional context in comments.

1 Comment

Geez. Total brain cramp. Somehow the one thing I didn't check was the first string coming into the function. Thanks, anubhava.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.