Linux 指令 >, <, >>, <<, &, &&, | & || 的用法

有時候會被 linux 指令搞得暈頭轉向 XD 所以記錄一下筆記

用 「>」 大於符號,代表將右邊的輸出結果導向右邊的某個檔案或指令,例如:

[sam@liho ~]$ echo "hello wolrd" > helloworld.txt
[sam@liho ~]$ cat helloworld.txt
hello wolrd

用 「< 」小於符號,代表將左邊的輸出結果導向左邊的某個檔案或指令,例如:

[sam@liho ~]$ read messages < helloworld.txt
[sam@liho ~]$ echo $messages
hello wolrd

用 「>> 」兩個大於符號,代表將左邊的輸出結果附加到某個檔案或指令,例如:

[sam@liho ~]$ echo "i'm sam." >> helloworld.txt
[sam@liho ~]$ cat helloworld.txt
hello wolrd
i'm sam.

用 「<< 」兩個小於符號,代表將右邊的輸出結果附加到某個檔案或指令 ,常見的用法就是透過 script 建立檔案,例如:

[sam@liho ~]$ cat <<EOF > foo.txt
i'm foo.
you are bar.
we are foo and bar.
EOF
[sam@liho ~]$ cat foo.txt
i'm foo.
you are bar.
we are foo and bar.

用 「&」and 符號,代表將程式放到背景執行:

[sam@liho ~]$ sleep 5 &
[1] 58352
[sam@liho ~]$
[1]  + done       sleep 5

用 「&&」兩個 and 符號,代表分開兩個指令,前面執行成功後再執行後面的指令,例如編譯程式:

[sam@liho ~]$ make && make install

例如檢查某目錄是否存在,存在就執行後面的指令:

[sam@liho ~]$ ls -ld bin
drwxr-xr-x  5 sam  sam  160 Nov 29 12:53 bin
[sam@liho ~]$ [[ -d "bin" ]] && echo "i found bin"
i found bin
[sam@liho ~]$ ls -ld foo
ls: foo: No such file or directory
[sam@liho ~]$ [[ -d "foo" ]] && echo "i found foo"
[sam@liho ~]$

用 「|」pipe line 符號,代表將執行結果導入另外一個指令:

[sam@liho ~]$ ls -ld bin --full-time
drwx------ 3 sam sam 11776 2023-11-14 14:26:39.000000000 +0800 bin
[sam@liho ~]$ ls -ld bin --full-time | awk '{print $6}'
2023-11-14

用 「||」兩個 pipe line 符號,代表分開兩個指令,前面執行失敗後才會執行後面的指令,例如:

[sam@liho ~]$ cat dog.txt || echo "there is no dog.txt"
cat: dog.txt: No such file or directory
there is no dog.txt

[sam@liho ~]$ cat dog.txt && echo "there is no dog.txt"
cat: dog.txt: No such file or directory

如果要將某目錄不存在建立好之後並改變一次權限可以用下列指令:

[sam@liho ~]$ [ -d /scratch/$USER ] || ( mkdir /scratch/$USER ; chmod 750 /scratch/$USER )

如果要將某目錄不存在建立好之後並每次都改變權限可以用下列指令:

[sam@liho ~]$ [ -d /scratch/$USER ] || mkdir /scratch/$USER ; chmod 750 /scratch/$USER

Leave a Reply

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.