寫在前面
本文將大致闡述當我們在命令行輸入一條完整的命令後(敲了回車鍵),到該命令真正開始執行這段時間內bash對輸入的文本命令所做的諸多操作。
講解shell編程的書籍多如牛毛,卻很少有哪一本會完整地介紹這些操作以及說清楚它們的前後發生順序,都是比較簡單地或者說強硬地羅列知識點而已。這就會導致一個非常嚴重的問題,那就是導致很多學習者很快就會迷失在零散的知識海洋中。因爲不瞭解當前學習的知識點處於諸多操作的哪個階段,自然就不會了解應該注意什麼,更不會了解它與前後階段的區別與聯繫,這樣學習就不會觸類旁通,最終的學習效果也是不夠深入。
但是一旦你瞭解了shell在開始執行命令之前對我們輸入的命令所做的諸多操作,並瞭解他們的執行順序的話,心中就有了一個很清晰的脈絡,就會很自然地瞭解所學的知識點當前處於哪個操作階段,以及與前後階段的關係,以這樣的方式學習,我相信每個人都不會在零散的知識點裏迷失方向,達到事半功倍的效果。
命令行處理流程
如果我們查閱bash的在線手冊,就會發現在3.1.1小節已經對bash處理一條命令的流程做了一個整體的概括。摘錄如下:
3.1.1 Shell Operation
---------------------
The following is a brief description of the shell's operation when it
reads and executes a command. Basically, the shell does the following:
1. Reads its input from a file (*note Shell Scripts::), from a string
supplied as an argument to the '-c' invocation option (*note
Invoking Bash::), or from the user's terminal.
2. Breaks the input into words and operators, obeying the quoting
rules described in *note Quoting::. These tokens are separated by
'metacharacters'. Alias expansion is performed by this step (*note
Aliases::).
3. Parses the tokens into simple and compound commands (*note Shell
Commands::).
4. Performs the various shell expansions (*note Shell Expansions::),
breaking the expanded tokens into lists of filenames (*note
Filename Expansion::) and commands and arguments.
5. Performs any necessary redirections (*note Redirections::) and
removes the redirection operators and their operands from the
argument list.
6. Executes the command (*note Executing Commands::).
7. Optionally waits for the command to complete and collects its exit
status (*note Exit Status::).
參考鏈接:
《Learning the bash Shell, 3rd Edition -- 7.3. Command-Line Processing》
《靈異的shell》
《卷1:第3章 The Bourne-Again Shell》《bash的展開》
《Shell:通過實例理解Bash命令替換和命令行處理流程》
《深入理解Linux Shell》《Bash命令行處理流程詳解》《Bash腳本語法泛述》
《Shell 參數擴展及各類括號在 Shell 編程中的應用》