In a function, I'm trying to extract the process ID from a line of text. Also, I'm trying to return that process 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"
The output is:
pid is pid is 9040 inside function outside of function
There are a few problems here:
- The two echo statements seem interwoven, indicating that the function and the main scope are running in paralell. Is this supposed to happen? Can it be turned off?
- The outside scope never gets the value of the process ID. As you can see, it's only printed once. Through testing, I know that it is only the echo inside of the function that is printing the process ID 9040. The outside scope seems to not have gotten the process ID.
What is the reason for these problems?