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.