在这里学到了很多东西,我带着一个令人困惑的问题回来了。我可以直接运行一些字符串操作命令并获得预期的结果。当我把它们放在一个函数中时,结果很糟糕。
我是否有脑痉挛而错过明显的症状?我的代码,测试:
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// /_}
结果:
function studentname = First_First
Now run same manips outside of function:
First
Last1 Last2
Last1_Last2_First
最后三行显示预期的字符串结果。为什么函数的名称会失败(设置为namefirst)?
非常感谢任何意见。
答案 0 :(得分:1)
问题在这里没有引用字符串:
get_name $studentname
由于$studentname
变量的值为First Last1 Last2
其中有空格,因此不带引号发送它只是在空格之前发送第一个单词,即将其称为:
get_name "First"
你的函数调用应该是:
get_name "$studentname"