- Bash Cookbook
- Ron Brash Ganesh Naik
- 274字
- 2021-07-23 19:17:32
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:
- my_function_global uses a global variable to return the command's return code
- my_function_return uses the reserved word, return, and a value (the command's return code)
- 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.
推薦閱讀
- 現(xiàn)代C++編程:從入門到實踐
- 程序員面試白皮書
- Design Principles for Process:driven Architectures Using Oracle BPM and SOA Suite 12c
- C語言程序設(shè)計習(xí)題解析與上機指導(dǎo)(第4版)
- SQL Server 2016從入門到精通(視頻教學(xué)超值版)
- 零基礎(chǔ)學(xué)Java程序設(shè)計
- Python機器學(xué)習(xí)經(jīng)典實例
- Getting Started with Python Data Analysis
- 實戰(zhàn)Java高并發(fā)程序設(shè)計(第3版)
- Mastering Android Development with Kotlin
- Java系統(tǒng)化項目開發(fā)教程
- Java網(wǎng)絡(luò)編程核心技術(shù)詳解(視頻微課版)
- SSM開發(fā)實戰(zhàn)教程(Spring+Spring MVC+MyBatis)
- Hands-On Nuxt.js Web Development
- ASP.NET開發(fā)寶典