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

Retrieving return codes and output

Up until now, we have been using a command called exit intermittently to exit scripts. For those of you who are curious, you may have already scoured the web to find out what this command does, but the key concept to remember is that every script, command, or binary exits with a return code. Return codes are numeric and are limited to being between 0-255 because an unsigned 8-bit integer is used. If you use a value of -1, it will return 255.

Okay, so return codes are useful in which ways? Return codes are useful when you want to know whether you found a match when performing a match (for example), and whether the command was completely successfully or there was an error. Let's dig into a real example using the ls command on the console:

$ ls ~/this.file.no.exist
ls: cannot access '/home/rbrash/this.file.no.exist': No such file or directory
$ echo $?
2
$ ls ~/.bashrc
/home/rbrash/.bashrc
$ echo $?
0

Notice the return values? 0 or 2 in this example mean either success (0) or that there are errors (1 and 2). These are obtained by retrieving the $? variable and we could even set it to a variable like this:

$ ls ~/this.file.no.exist
ls: cannot access '/home/rbrash/this.file.no.exist': No such file or directory
$ TEST=$?
$ echo $TEST
2

From this example, we now know what return codes are, and how we can use them to utilize results returned from functions, scripts, and commands.

主站蜘蛛池模板: 辽宁省| 淅川县| 马尔康县| 长白| 盐源县| 来安县| 宝山区| 南岸区| 宣化县| 崇义县| 罗甸县| 洛南县| 三原县| 新田县| 石楼县| 屯留县| 怀宁县| 金堂县| 巴彦淖尔市| 九寨沟县| 灵川县| 通城县| 罗源县| 阿拉善左旗| 西峡县| 台东市| 古丈县| 卓资县| 拉孜县| 弥勒县| 望谟县| 长海县| 湟源县| 库伦旗| 深泽县| 饶阳县| 华宁县| 江油市| 社旗县| 定日县| 南皮县|