Software engineering notes

Linux Commands

Console 快捷鍵

畫面

刪除

移動

指令

其他

開關機

背景執行

放入背景

ctrl + z

看背景有哪些程式在執行

$ jobs
[1] + Stopped                    vim test

叫出第一個背景的程式

$ fg %1

停止在背景執行的第一個程式

$ kill -9 %1
$ jobs
[1] + Killed                     vim test

使用者

線上使用者

$ who
webadmin pts/0        Apr 20 17:51 (61.58.172.120)
root     pts/1        Apr 20 18:46 (61.58.172.120)

$ w
18:46:50 up 103 days, 22 min,  1 user,  load average: 0.00, 0.00, 0.00
USER     TTY      FROM              LOGIN@   IDLE   JCPU   PCPU WHAT
webadmin pts/0    180-176-112-131. 18:40    0.00s  0.00s  0.00s w

目前使用者

whoami

current user’s bash pid

explain:

$ echo $(echo $BASHPID $$)      $$       $BASHPID
              25680    16920    16920    16920
#             |        |        |        |
#             |        |        |        -- $BASHPID outside of the subshell
#             |        |        -- $$ outside of the subshell
#             |        -- $$ inside of the subshell
#             -- $BASHPID inside of the subshell

ref: https://unix.stackexchange.com/questions/62231/bashpid-and-differ-in-some-cases

pid

印出當下執行指令的 pid

$ ll /proc/self & echo $!
[1] 20424
20424
lrwxrwxrwx 1 root root 0 Dec 12 06:34 /proc/self -> 20424
[1]+  Done                    ls --color=auto -la /proc/self

mkdir

自動建立階層目錄 recursive mkdir

mkdir -p /var/www/log/website

-p, –parents no error if existing, make parent directories as needed

md5

md5 test.txt
MD5 (test.txt) = b79a5759ca168122b9ebd1b57e4a883b

或

md5sum test.txt

ls

顯示目錄下的檔案權限, 擁有者..等等

ls -l

檔案大小那邊會換算成我們習慣的方式(G, M, K)

ls -lh
drwxr-xr-x 15 webadmin root 4.0K Mar 19 21:09 application
drwxr-xr-x  6 webadmin root 4.0K Apr  7 21:25 assets

顯示目錄下的檔案(包含隱藏檔)

ls -a

ls | more    # 分頁 q : 離開
ls | less    # 分頁 (操作如同vim,但不需要加ctrl)
             # d : 下12筆,
             # b、w : 上一頁,
             # f : 下一頁,
             # j 、e : 下一筆,
             # g : 回到第一筆,
             # k : 上一筆,
             # h : help

顯示檔案的inode id

$ ls -ia
1451762 .           1443270 .mysql_history  1576628 assets
1451760 ..          1443190 .php_history    1443160 djfl
1577046 .cache      1443425 .ssh            1443313 index.php
1443151 .git        1576655 .vim            1443315 license.txt
1443307 .gitconfig  1442269 .viminfo        1576661 system
1443272 .gitignore  1443276 .vimrc          1577048 test
1443312 .htaccess   1576553 application     1576831 user_guide

檔案型別, identifiers:

pwd

目前目錄位置

$ pwd
/home/ec2-user/my_project

如果是連結檔, 加上-P可以顯示真實路徑

$ pwd -P
/home/apps/src/my_project

cd

如果是連結檔, 加上-P可以進入到真實路徑

$ cd -P my_project/

tail

tail -f -n 100 log-2013-06-21.php     #當檔案發生變動時印出檔尾末100行

限制字數

tail -f log-2017-10-12.php | cut -c -80

scp 遠端複製檔案

一般用法 : 將本機檔案

$ scp .tmux.conf username@example.com:~/.tmux.conf

指定 port

scp -P 4123 remote_user@192.168.37.21:~/test/t.txt t.txt

使用vim為預設編輯器

export EDITOR=vim
export VISUAL=vim

chown

改變群組及擁有者

drwxr-xr-x 4 root     root 4096 Apr 20 18:46 test1        #原本擁有者及群組都是root

$ chown webadmin:webadmin test1                           #將擁有者及群組都改為webadmin
drwxr-xr-x 4 webadmin webadmin 4096 Apr 20 18:46 test1    #結果擁有者及群組都是webadmin

省略群組, 只會改擁有者

drwxr-xr-x 4 webadmin root 4096 Apr 20 18:46 test1          #原本擁有者為webadmin,群組為root

$ chown root test1                                          #只輸入root(省略群組)
drwxr-xr-x 4 root     root 4096 Apr 20 18:46 test1          #結果只會修改擁有者,群組不變

chgrp

drwxr-xr-x 4 webadmin webadmin 4096 Apr 20 18:46 test1      #原本群組為webadmin

$ chgrp root test1                                          #將群組改為root
drwxr-xr-x 4 webadmin root 4096 Apr 20 18:46 test1          #結果群組改為root了

chmod

改為 777

drwxr-xr-x 4 webadmin root 4096 Apr 20 18:46 test1          #原本權限為755

$ chmod 777 test1                                           #將權限改為777
drwxrwxrwx 4 webadmin root 4096 Apr 20 18:46 test1          #結果權限被改為777了

全部加上執行權限 (a+x)

-rw-r--r-- 1 webadmin root   20 Apr 21 11:18 test.php       #原本

$ chmod +x test.php                                         #全部都加上執行權限
-rwxr-xr-x 1 webadmin root   20 Apr 21 11:18 test.php       #結果

只有 user 加上執行權限

-rw-rw-rw- 1 webadmin root   20 Apr 21 11:18 test.php       #原本

$ chmod u+x test.php                                        #只有擁有者加上執行權限
-rwxrw-rw- 1 webadmin root   20 Apr 21 11:18 test.php       #結果

find

Execute a command when matching the files

find src/* -type f -name '*.php' -exec php -l {} \;

watch -n 1

每秒執行一次

watch -n 1 cat filename
watch -n 1 tail -5 /etc/projid
watch -n 1 'netstat -ant | grep "ESTABLISHED" | wc -l'

-n, –interval seconds to wait between updates

locale 列出語言檔

locale -a

screen

視窗

分割視窗

copy mode

tmux

ref: more shortcuts

uname

顯示作業系統

$ uname
Linux

顯示作業系統版本

$ uname -a
Linux ip-10-0-11-161 4.4.35-33.55.amzn1.x86_64 #1 SMP Tue Dec 6 20:30:04 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

顯示幾位元

$ uname -m
x86_64 = 64 bit

i686 = 32 bit

test

test -e /dmtsai

[1] 關於某個檔名的『檔案類型』判斷,如 test -e filename 表示存在否

[2] 關於檔案的權限偵測,如 test -r filename 表示可讀否 (但 root 權限常有例外)

[3] 兩個檔案之間的比較,如: test file1 -nt file2

[4] 關於兩個整數之間的判定,例如 test n1 -eq n2

[5] 判定字串的資料

註: -n 亦可省略

[6] 多重條件判定,例如: test -r filename -a -x filename

cat

Append one file to another

cat d.txt >> q.txt

顯示檔案內容及行數

cat -n phpinfo.php

whereis

尋找檔案

$ whereis bin
bin: /usr/local/bin

whereis 利用曾經找過的系統資訊內的資料去找檔案,所以速度會很快 * 不過,如果 whereis 找不到的話,並不代表該檔案真的不存在!

系統資訊

系統訊息

$ cat /etc/*release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=13.04
DISTRIB_CODENAME=raring
DISTRIB_DESCRIPTION="Ubuntu 13.04"
NAME="Ubuntu"
VERSION="13.04, Raring Ringtail"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 13.04"
VERSION_ID="13.04"
HOME_URL="http://www.ubuntu.com/"
SUPPORT_URL="http://help.ubuntu.com/"
BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"

看系統內核等信息

$ uname -a
Linux virtualBox 3.8.0-30-generic #44-Ubuntu SMP Thu Aug 22 20:52:24 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux

查看系統資訊

$ more /proc/version
Linux version 2.6.32-042stab059.7 (root@rh6-build-x64) (gcc version 4.4.6 201203
05 (Red Hat 4.4.6-4) (GCC) ) #1 SMP Tue Jul 24 19:12:01 MSK 2012

等同 cat /proc/version

查看目前Linux版本

$ cat /etc/issue
Ubuntu 12.04.1 LTS \n \l

顯示linux版本

$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 12.04.1 LTS
Release:        12.04
Codename:       precise

pstree

arguments:

列出此 pid 下的 process tree

$ pstree 18082
-+= 18082 test bash /Users/test/projects/test/run.sh
 \--- 18083 test ./test_pid

kill

強制中斷 process

kill

kill 11372 (pid)
    -9       KILL (non-catchable, non-ignorable kill)

killall (kill processes by name)

killall redis

查看 Process 是否執行中(其實就是看有沒有 pid)

pidof redis

lsusb

列出連接 usb 的週邊設備

$ lsusb
Bus 001 Device 002: ID 80ee:0021 VirtualBox USB Tablet
Bus 001 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub

apropos

apropos searches a set of database files containing short descriptions of system commands for keywords and displays the result on the standard output.

$ apropos awk
a2p(1)                   - Awk to Perl translator
awk(1)                   - pattern-directed scanning and processing language
English(3pm)             - use nice English (or awk) names for ugly punctuation variables
a2p(1)                   - Awk to Perl translator
awk(1)                   - pattern-directed scanning and processing language

cpu info

$ cat /proc/cpuinfo
processor       : 0
vendor_id       : GenuineIntel
cpu family      : 6
model           : 45
model name      : Intel(R) Xeon(R) CPU E5-2650 0 @ 2.00GHz
stepping        : 7
microcode       : 0x70a
cpu MHz         : 1799.999
cache size      : 20480 KB
(...略...)

Memory info

$ free -h
             total       used       free     shared    buffers     cached
Mem:          3.8G       3.2G       646M         0B       1.1G       1.3G
-/+ buffers/cache:       914M       3.0G
Swap:         4.0G       121M       3.9G

cpu core count

nproc
或
cat /proc/cpuinfo | grep process

cpu information

lscpu
或
cat /proc/cpuinfo

wc 程序從標準輸入流或文件列表讀取文件,並生成一個或多個下列統計信息

count line

netstat -ant | grep "ESTABLISHED" | wc -l
wc -l import.txt

count file characters

wc -c off.xml

less color

ls --color | less

結果 :

ESC[0mESC[01;34mc1ESC[0m
ESC[01;34mc2ESC[0m
ESC[01;34mc3ESC[0m

加上 -R, 結果就會有顏色了

 --color | less -R

-R or –RAW-CONTROL-CHARS : Like -r, but only ANSI “color” escape sequences are output in “raw” form. Unlike -r, the screen appearance is maintained correctly in most cases.

sudo command not found

有時候拿 sudo 去執行某些指令時, 會發生此問題, 因為 sudo 並沒有設定那些指令的路徑, 把它加上去即可

sudo env PATH=$PATH

去除顏色符號 e.g. ^[[1;33mWhich environment? -^[[0m

cat /tmp/tt.log | perl -pe 's/\e[\[\(][0-9;]*[mGKFB]//g' > /tmp/tt2.log

檔案字尾出現 windows 換行符號 ^M

因為 windows 與 linux 字尾符號不同的關係, 可藉由 dos2unix 修正

基本用法

dos2unix t1.php t2.php t3.php

修正所有檔案(recursive)

find . -type f -exec dos2unix {} \;

或用 vim 修正, 但僅限於可以看到 ^M 在字尾

:%s/\r//g

如果用 vim 開啟看不到 ^M 在字尾要改用

sed -i 's/\r$//' wrap-trim.log

cowsay

test@test:/tmp$ echo "Hello World!" | cowsay
 ______________
< Hello World! >
 --------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||

test@test:/tmp$ echo "????????????" | cowthink
 ______________
( ???????????? )
 --------------
        o   ^__^
         o  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||

ulimit

設定每個 user 能使用的資源 e.g. 開檔數量

To set the size of core dumps to unlimited, use:

ulimit –c unlimited

uptime

server 總共執行多久了

 10:53:24 up 34 days,  7:47,  1 user,  load average: 0.09, 0.06, 0.06

load average 代表是系統的平均負荷

後面的3個數字分別代表 1, 5, 15 分鐘。0 CPU 空閒, 1 代表 cpu 滿載, 數值有可能會大於 1

tee

將標準輸出分流出來, 不會影斷原本的標準輸出

$ echo 'Hello World' | tee t1.txt
Hello World
$ cat t1.txt
Hello World

-a: 累加, 而不是覆寫

date

輸出 timestamp

date +%s

timestamp to datetime

date -d @1481605585
Tue Dec 13 05:06:25 UTC 2016

datetime to timestamp

date -d '2018/05/09 09:30:30' +"%s"
date -d 'TZ="UTC+9" 2018-07-04 02:53:06' +%s   // 會幫你把 datetime +9 再轉成 timestamp
date -d 'TZ="UTC-9" 2018-07-04 02:53:06' +%s   // 如果 datetime 是日本時間, 再轉成 timestamp 這樣才對

format

date +%Y-%m-%d                  // 2016-12-24
date +%Y-%m-%d:%H:%M:%S`        // 2016-12-24:10:28:58

開機自動執行

/etc/rc.d/rc.local :

touch /var/lock/subsys/local   # 原本就存在的,新增的寫在下面
/etc/init.d/nginx start
/etc/init.d/php-fpm start

lsof

欄位說明請參考: http://man7.org/linux/man-pages/man8/lsof.8.html

$ sudo lsof /dev/ptmx
[sudo] password for test_user:
COMMAND     PID         USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
sshd       1134         root    5u   CHR    5,2      0t0   86 /dev/ptmx

檔案刪除了, 空間卻沒有被釋放, 還是被維持 open 的狀態, 所以空間釋放不了, 用這個指令查可以把它找出來, 再把這個 process kill 掉就行了

sudo lsof | grep deleted

my-monitor    8172  9770       root  156r      REG              202,1 1359484070     276282 /home/apps/example/test.log (deleted)
my-monitor    8172  9770       root  163r      REG              202,1 1359484070     276282 /home/apps/example/test.log (deleted)
my-monitor    8172  9770       root  191r      REG              202,1 1359484070     276282 /home/apps/example/test.log (deleted)
my-monitor    8172  9770       root  212r      REG              202,1 1359484070     276282 /home/apps/example/test.log (deleted)
my-monitor    8172  9770       root  214r      REG              202,1 1359484070     276282 /home/apps/example/test.log (deleted)
my-monitor    8172  9770       root  226r      REG              202,1 1359484070     276282 /home/apps/example/test.log (deleted)

free up memory

linux:

echo 3 > /proc/sys/vm/drop_caches

mac:

sudo purge

hexdump: 將檔案(一般檔案或 binary) 輸出成 16 進制

-C 輸出三列(文字偏移量,16進制,ASCII)

hexdump -C test.txt
00000000  30 31 32 33 34 35 36 37  38 39 41 42 43 44 45 46  |0123456789ABCDEF|
00000010  47 48 49 4a 4b 4c 4d 4e  4f 50 51 52 53 54 55 56  |GHIJKLMNOPQRSTUV|
00000020  57 58 59 5a 0a                                    |WXYZ.|
00000025

最後的 0a 是換行字元, 可用 ASCII 對應表來看

xxd: 將檔案輸出成 16 進制或 2 進制

不加參數, 輸出成 16 進制

xxd test.txt
0000000: 3031 3233 3435 3637 3839 4142 4344 4546  0123456789ABCDEF
0000010: 4748 494a 4b4c 4d4e 4f50 5152 5354 5556  GHIJKLMNOPQRSTUV
0000020: 5758 595a 0a                             WXYZ.

-b 輸出成 2 進制

xxd -b test.txt
0000000: 00110000 00110001 00110010 00110011 00110100 00110101  012345
0000006: 00110110 00110111 00111000 00111001 01000001 01000010  6789AB
000000c: 01000011 01000100 01000101 01000110 01000111 01001000  CDEFGH
0000012: 01001001 01001010 01001011 01001100 01001101 01001110  IJKLMN
0000018: 01001111 01010000 01010001 01010010 01010011 01010100  OPQRST
000001e: 01010101 01010110 01010111 01011000 01011001 01011010  UVWXYZ
0000024: 00001010

最後的 00001010 = Hexadecimal 0a 是換行字元

ln -s {source_path} {destination_path}

e.g.

ln -s /tmp/QQ /tmp/cc

e.g.

readlink -f /proc/self/

pushd/popd: very useful command to allow you to roam the directory.

pushd /tmp          # put current path in FIFO Queue and go to /tmp
popd                # go to that path that comes from FIFO Queue

Redirections (重定向)

ref: http://wanggen.myweb.hinet.net/ch4/ch4.html#redirection

clusterssh 一次管理多台主機安裝及設定

  sudo apt-get install clusterssh

執行 :

  sudo cssh -l root 192.168.1.200 192.168.1.201

設定成設定檔 :

$ sudo nano /etc/clusters
clusters = testcluster
testcluster = 192.168.1.200 192.168.1.201

$ sudo cssh -l root testcluster