Bash shell basics — inline execution
In the Bash shell, to obtain the value of an environment variable we use the dollar (ie $) character.
echo $PATH
A similar technique can be used in a pipeline, that has multiple commands.
# output from pgrep is passed back to the ps command
ps -o pid,euser $(pgrep -u root systemctl)
Similarly, inside a Bash script, to get the output of a function we can use the dollar character with parenthesis (ie $() ). This feature is called an inline execution.
In the Bash shell, inline execution is used to pass output back to the calling function, or calling statement and can be a useful feature for your next Bash shell script.
Inline execution
To control the flow of a script, we can use a For statement, and inline execution can be used.
#!/bin/bash
# flow control involving inline execution
for pid in $(ps --no-headers -o pid,euser $(pgrep -u root)|awk '{print $1}')
do
echo $pid
# do something here
# kill $pid
done
exit
So the pipeline returns the output, via an inline execution, to the For statement.
The same technique can be performed when calling a function, and you want to return the standard output of the function to the calling function.
#!/bin/bash
function func {
local a='func: a'
# echo the standard output back to the calling function
echo $a
}
main() {
# call a function
local z="$(func)"
# echo the output of the function
echo $z
}
main
exit
Using an inline execution, the output of the function is returned to the calling function (ie main).
Using the same technique, the output of a function can be retuned to an If statement.
#!/bin/bash
function func {
local a=$(ps --no-headers -o pid,euser $(pgrep -u $1 $2)|awk '{print $1}')
# echo the standard output back to the calling function
echo $a
}
main() {
# process the whole list of pipelines
# but exit when a pipeline status returns an error (ie >0)
if func oracle java && func postfix java
then
echo 'list execution was a success: pipestatus='$PIPESTATUS
else
echo 'list execution failed: pipestatus='$PIPESTATUS
fi
}
main
exit
Using the inline execution, the output of the function is returned to an If statement.
The If statement treats the output as a pipeline, so each pipeline is executed.
The If statement evaluates the list of pipelines, and if the pipestatus is zero, then the execution of the list of pipelines is a success.
Reference
Checkout some other Bash articles here: