我是 shell 脚本的新手,我正在尝试创建一个简单的函数,它将返回作为参数传递的连接的两个字符串。我尝试使用以下代码
function getConcatenatedString() {
echo "String1 $1"
echo "String2 $2"
str=$1/$2
echo "Concatenated String ${str}"
echo "${str}"
}
//我正在调用上面的函数
constr=$(getConcatenatedString "hello" "world")
echo "printing result"
echo "${constr}"
echo "exit"
用上面的代码运行脚本时,我看到下面的输出,
printing result
String1 hello
String2 world
Concatenated String hello/world
hello/world
exit
如果你看一下我先调用函数然后回显“打印结果”语句的代码,但结果是先出现“打印结果”并回显函数内部的语句。下面的语句是调用函数吗
constr=$(getConcatenatedString "hello" "world")
或
echo ${constr}
正在调用函数?
因为如果我注释掉#echo ${constr} 那么什么都不会得到回应!!!请澄清一下。
最佳答案
首先是调用函数并将输出的所有(四个echo
语句)存储到$constr
中。
然后,返回后,回显前导码打印结果
、$constr
(由四行组成)和退出消息。
这就是 $()
的工作原理,它从包含的命令中捕获整个标准输出。
听起来您想在控制台上看到一些 echo
语句,而不是用 $()
捕获它们。我认为您应该能够为此将它们发送到标准错误:
echo "String1 $1" >&2
关于linux - shell脚本函数返回一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11758368/