官术网_书友最值得收藏!

Return code 101

Dig into your terminal and create the following Bash script:

#!/bin/bash
GLOBAL_RET=255

function my_function_global() {
ls /home/${USER}/.bashrc
GLOBAL_RET=$?
}
function my_function_return() {
ls /home/${USER}/.bashrc
return $?
}
function my_function_str() {
local UNAME=$1
local OUTPUT=""
if [ -e /home/${UNAME}/.bashrc ]; then
OUTPUT='FOUND IT'
else
OUTPUT='NOT FOUND'
fi
echo ${OUTPUT}
}

echo "Current ret: ${GLOBAL_RET}"
my_function_global "${USER}"
echo "Current ret after: ${GLOBAL_RET}"
GLOBAL_RET=255
echo "Current ret: ${GLOBAL_RET}"
my_function_return "${USER}"
GLOBAL_RET=$?
echo "Current ret after: ${GLOBAL_RET}"

# And for giggles, we can pass back output too!
GLOBAL_RET=""
echo "Current ret: ${GLOBAL_RET}"
GLOBAL_RET=$(my_function_str ${USER})
# You could also use GLOBAL_RET=`my_function_str ${USER}`
# Notice the back ticks "`"
echo "Current ret after: $GLOBAL_RET"
exit 0

The script will output the following before exiting with a return code of 0 (remember that ls returns 0 if run successfully):

rbrash@moon:~$ bash test.sh
Current ret: 255
/home/rbrash/.bashrc
Current ret after: 0
Current ret: 255
/home/rbrash/.bashrc
Current ret after: 0
Current ret:
Current ret after: FOUND IT
$

In this section, there are three functions that leverage three concepts:

  1. my_function_global uses a global variable to return the command's return code
  2. my_function_return uses the reserved word, returnand a value (the command's return code)
  3. my_function_str uses a fork (a special operation) to execute a command and get the output (our string, which is echoed)
For option 3, there are several ways to get a string back from a function, including using the  eval  keyword. However, when using fork, it is best to be aware of the resources it may consume when running the same command many times just to get the output.
主站蜘蛛池模板: 浦东新区| 淮北市| 和平县| 五峰| 剑阁县| 呼和浩特市| 临海市| 竹北市| 崇义县| 仁寿县| 河北省| 民县| 定西市| 鹤岗市| 息烽县| 长泰县| 高要市| 龙泉市| 理塘县| 新和县| 三都| 新源县| 奈曼旗| 平湖市| 渝北区| 普安县| 县级市| 临潭县| 阿勒泰市| 阿拉善右旗| 新昌县| 大方县| 柘城县| 侯马市| 余姚市| 邳州市| 轮台县| 溆浦县| 临朐县| 红河县| 蒙城县|