Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม Bash

เชี่ยวชาญ Bash Exit Status: บทช่วยสอนปฏิบัติ

ในบทความ Bash Introduction เราเรียนรู้ว่า Shell-script File มี List of Commands ที่จะ Execute โดย Shell Interpreter ในบทความนี้ มาทบทวน Shell Commands และ Internal ของมัน

Command คือ Sequence of Words Word แรกบ่งชี้ Command ที่จะ Execute และ Words ที่เหลือส่งเป็น Arguments โดย Arguments อาจเป็น Options หรือ Parameters ของ Command

Unix Commands ทั่วไปที่ Execute ที่ Command Line เป็น Shell Commands เช่น ls, lpr และ grep

$ ls -alF
$ lpr filename
$ grep "string" filename

Shell Command Exit Status

Return Value ของ Command คือ Exit Status หรือ 128 + N ถ้า Command ถูก Terminated โดย Signal N Exit Status ใช้ตรวจสอบ Result (Success/Failure) ของ Command Execution ถ้า Exit Status เป็นศูนย์ Command สำเร็จ ถ้า Command ล้มเหลว Exit Status จะเป็น Non-zero

Exit Value Exit Status
0 (Zero) Success
Non-zero Failure
2 Incorrect Usage
127 Command Not Found
126 Not an Executable

$? Shell Variable

Shell Variable ชื่อ $? เป็น Special Built-in Variable ที่มี Exit Status ของ Last Command Executed

  • หลัง Shell Function Execution, $? คืนค่า Exit Status ของ Last Command Executed ใน Function
  • หลัง Shell Script Execution, $? คืนค่า Exit Status ของ Last Command Executed ใน Script

Sample Shell Script อธิบาย Shell-Command Exit Status

exitstatus.sh Shell-script ต่อไปนี้แสดงตัวอย่าง Exit Status ต่างๆ

$ cat exitstatus.sh
#! /bin/bash
echo -e "Successful execution"
echo -e "====================="
echo "hello world"
# Exit status returns 0, because the above command is a success.
echo "Exit status"
$?
echo -e "Incorrect usage"
echo -e "====================="
ls --option  # Incorrect usage, so exit status will be 2.
echo "Exit status"
$?
echo -e "Command Not found"
echo -e "====================="
bashscript  # Exit status returns 127, because bashscript command not found
echo "Exit status"
$?
echo -e "Command is not an executable"
echo -e "============================="
ls -l execution.sh
./execution.sh  # Exit status returns 126, because its not an executable.
echo "Exit status"
$?

รัน exitstatus.sh เพื่อดู Exit Status ต่างๆ จาก Sample Shell Script

$ bash exitstatus.sh
Successful execution
=====================
hello world
Exit status
0
Incorrect usage
=====================
ls: unrecognized option `--option'
Try `ls --help' for more information.
Exit status
2
Command Not found
=====================
exitstaus.sh: line 15: bashscript: command not found
Exit status
127
Command is not an executable
=============================
-rw-r--r-- 1 root root 659 Mar 9 13:36 execution.sh
exitstatus.sh: line 21: ./execution.sh: Permission denied
Exit status
126

Note: Checking the return value of a function or a command is one of the main responsibility of a programmer. This should become your second nature while writing any code.

If you liked this article, please bookmark it on del.icio.us and Stumble it.