在一个函数中,我试图从一行文本中提取进程ID。另外,我正在尝试返回该进程ID:
#!/bin/bash
regex="[a-z]* ([0-9]+) .*"
indexRawRow="sahandz 9040 other stuff comes here"
getPidFromRow() {
if [[ $1 =~ $regex ]]
then
pid=${BASH_REMATCH[1]}
else
pid=""
fi
echo "pid is $pid inside function"
return $pid
}
processId=$(getPidFromRow "$indexRawRow")
echo "pid is $processId outside of function"
输出为:
pid is pid is 9040 inside function outside of function
这里有一些问题:
这些问题的原因是什么?
答案 0 :(得分:2)
您的假设在这里很复杂,在processId
输出的变量$(..)
中看到的是echo
语句的输出,而 not 来自功能的return
版的值。
您根本无法从bash
中的函数返回字符串。来自0-255
的无符号整数代码。如果只从函数中返回匹配的组,则省略return语句,只打印匹配的组
getPidFromRow() {
# Your other code here
# ..
printf '%d\n' "$pid"
}