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

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.

主站蜘蛛池模板: 江达县| 潞城市| 榆社县| 虞城县| 蒙山县| 廊坊市| 什邡市| 台前县| 读书| 喜德县| 梅州市| 通辽市| 称多县| 天津市| 芦山县| 卢湾区| 慈溪市| 边坝县| 马关县| 电白县| 台东市| 清流县| 阳江市| 永登县| 石家庄市| 怀集县| 新密市| 元朗区| 东丽区| 洱源县| 沙田区| 五河县| 金门县| 砀山县| 德清县| 文安县| 南阳市| 启东市| 永定县| 社旗县| 丹东市|