{{{ #!html
實作四: Bash Shell Script 實作練習
}}} [[PageOutline]] ◢ <[wiki:YM_Course_2009/Lab3 實作三]> | <[wiki:YM_Course_2009 回課程大綱]> ▲ | <[wiki:YM_Course_2009/Lab5 實作五]> ◣ = 1. 重新導向練習 = * 首先,讓我們來練習 I/O 重新導向表上的指令。 * 使用 > 或 1> 把 ls 指令的 STDOUT 結果導向到 file 與 file2 這兩個檔案,結果是相似的。 * 你可能會注意到 file 裡有出現 file,file2 裡才有出現 file2,代表檔案是先產生,然後才執行 ls 指定的。 {{{ ubuntu@ubuntu:~$ ls > file ubuntu@ubuntu:~$ cat file file profile temp temp2 ubuntu@ubuntu:~$ ls 1> file2 ubuntu@ubuntu:~$ cat file2 file file2 profile temp temp2 }}} * 使用 2> 把 ls 指令的 STDERR 導向到 file3,你會發現 file3 的內容是空的,因為並沒有出現錯誤,而 STDOUT 的結果還是出現在畫面上。 {{{ ubuntu@ubuntu:~$ ls 2> file3 file file2 file3 profile temp temp2 ubuntu@ubuntu:~$ cat file3 }}} * 我們刻意下錯指令,例如:ls temp3 來產生 STDERR 輸出。 {{{ ubuntu@ubuntu:~$ ls temp3 2> file4 ubuntu@ubuntu:~$ cat file4 ls: cannot access temp3: No such file or directory }}} * 我們刻意下指令,例如:ls temp temp3 來同時產生 STDOUT 與 STDERR 輸出。 {{{ ubuntu@ubuntu:~$ ls temp temp3 ls: cannot access temp3: No such file or directory temp: ubuntu@ubuntu:~$ ls temp temp3 > file5 2> file6 ubuntu@ubuntu:~$ cat file5 temp: ubuntu@ubuntu:~$ cat file6 ls: cannot access temp3: No such file or directory ubuntu@ubuntu:~$ ls temp temp3 > file7 2>&1 ubuntu@ubuntu:~$ cat file7 ls: cannot access temp3: No such file or directory temp: ubuntu@ubuntu:~$ ls temp temp3 2> file8 1>&2 ubuntu@ubuntu:~$ cat file8 ls: cannot access temp3: No such file or directory temp: }}} * 因為 file8 存在,因此當我們用 >> 來重新導向 cat file 指令的 STDOUT 結果,會附加到 file8 檔案後面。 {{{ ubuntu@ubuntu:~$ cat file >> file8 ubuntu@ubuntu:~$ cat file8 ls: cannot access temp3: No such file or directory temp: file profile temp temp2 }}} * 使用 2>> 把 ls temp temp3 的 STDERR 附加到 file8 {{{ ubuntu@ubuntu:~$ ls temp temp3 2>> file8 temp: ubuntu@ubuntu:~$ cat file8 ls: cannot access temp3: No such file or directory temp: file profile temp temp2 ls: cannot access temp3: No such file or directory }}} * cat 用 < 來讀取 STDIN {{{ ubuntu@ubuntu:~$ cat < /etc/profile }}} * 使用 << EOF 來一次輸入很多資料 {{{ ubuntu@ubuntu:~$ cat > file9 << EOF this is a test 使用 << EOF 來一次輸入很多資料 EOF ubuntu@ubuntu:~$ cat file9 this is a test 使用 << EOF 來一次輸入很多資料 }}} }}}