| | 8 | |
| | 9 | = 1. 重新導向練習 = |
| | 10 | |
| | 11 | * 首先,讓我們來練習 I/O 重新導向表上的指令。 |
| | 12 | * 使用 > 或 1> 把 ls 指令的 STDOUT 結果導向到 file 與 file2 這兩個檔案,結果是相似的。 |
| | 13 | * 你可能會注意到 file 裡有出現 file,file2 裡才有出現 file2,代表檔案是先產生,然後才執行 ls 指定的。 |
| | 14 | {{{ |
| | 15 | ubuntu@ubuntu:~$ ls > file |
| | 16 | ubuntu@ubuntu:~$ cat file |
| | 17 | file |
| | 18 | profile |
| | 19 | temp |
| | 20 | temp2 |
| | 21 | ubuntu@ubuntu:~$ ls 1> file2 |
| | 22 | ubuntu@ubuntu:~$ cat file2 |
| | 23 | file |
| | 24 | file2 |
| | 25 | profile |
| | 26 | temp |
| | 27 | temp2 |
| | 28 | }}} |
| | 29 | * 使用 2> 把 ls 指令的 STDERR 導向到 file3,你會發現 file3 的內容是空的,因為並沒有出現錯誤,而 STDOUT 的結果還是出現在畫面上。 |
| | 30 | {{{ |
| | 31 | ubuntu@ubuntu:~$ ls 2> file3 |
| | 32 | file file2 file3 profile temp temp2 |
| | 33 | ubuntu@ubuntu:~$ cat file3 |
| | 34 | }}} |
| | 35 | * 我們刻意下錯指令,例如:ls temp3 來產生 STDERR 輸出。 |
| | 36 | {{{ |
| | 37 | ubuntu@ubuntu:~$ ls temp3 2> file4 |
| | 38 | ubuntu@ubuntu:~$ cat file4 |
| | 39 | ls: cannot access temp3: No such file or directory |
| | 40 | }}} |
| | 41 | * 我們刻意下指令,例如:ls temp temp3 來同時產生 STDOUT 與 STDERR 輸出。 |
| | 42 | {{{ |
| | 43 | ubuntu@ubuntu:~$ ls temp temp3 |
| | 44 | ls: cannot access temp3: No such file or directory |
| | 45 | temp: |
| | 46 | ubuntu@ubuntu:~$ ls temp temp3 > file5 2> file6 |
| | 47 | ubuntu@ubuntu:~$ cat file5 |
| | 48 | temp: |
| | 49 | ubuntu@ubuntu:~$ cat file6 |
| | 50 | ls: cannot access temp3: No such file or directory |
| | 51 | ubuntu@ubuntu:~$ ls temp temp3 > file7 2>&1 |
| | 52 | ubuntu@ubuntu:~$ cat file7 |
| | 53 | ls: cannot access temp3: No such file or directory |
| | 54 | temp: |
| | 55 | ubuntu@ubuntu:~$ ls temp temp3 2> file8 1>&2 |
| | 56 | ubuntu@ubuntu:~$ cat file8 |
| | 57 | ls: cannot access temp3: No such file or directory |
| | 58 | temp: |
| | 59 | }}} |
| | 60 | * 因為 file8 存在,因此當我們用 >> 來重新導向 cat file 指令的 STDOUT 結果,會附加到 file8 檔案後面。 |
| | 61 | {{{ |
| | 62 | ubuntu@ubuntu:~$ cat file >> file8 |
| | 63 | ubuntu@ubuntu:~$ cat file8 |
| | 64 | ls: cannot access temp3: No such file or directory |
| | 65 | temp: |
| | 66 | file |
| | 67 | profile |
| | 68 | temp |
| | 69 | temp2 |
| | 70 | }}} |