Joldnine / joldnine.github.io

My github.io blog repo. https://joldnine.github.io
2 stars 1 forks source link

Frequently Used Linux Commands #7

Open Joldnine opened 6 years ago

Joldnine commented 6 years ago

Some common commands and command tools in the Unix-like system.

Basics

$ mkdir $HOME/testFolder

$ cd $HOME/testFolder

$ cd ../

$ mv $HOME/testFolder /var/tmp

$ rm -rf /var/tmp/testFolder

$ ls /etc

$ touch ~/testFile

$ ls ~

$ cp ~/testFile ~/testNewFile

$ rm ~/testFile

$ cat ~/.bash_history

# Find a string in a file.
grep 'root' /etc/passwd

# Find a string under the folder.
$ grep -r 'linux' /var/log/

$ grep -r "linux" /var/log/ --include="*.log"

$ cat /etc/passwd | grep 'root'

$ ls /etc | grep 'ssh'

$ echo 'Hello World' > ~/test.txt

$ ping -c 4 cloud.tencent.com

$ ps -aux | grep 'ssh'

netstat

netstat 命令用于显示各种网络相关信息,如网络连接, 路由表, 接口状态等等

# 列出所有处于监听状态的tcp端口
$ netstat -lt

# 查看所有的端口信息, 包括 PID 和进程名称
$ netstat -tulpn

refs: 腾讯云实验室

tar

tar 是一个简单的解压缩工具。其中tar后缀代表只是把文件打包在一起,gz后缀代表压缩。

# 压缩
$ tar -cvzf <target_file> <source file/folder>

# 解压缩
$ tar -xvzf <source_file>

# 打包但是不压缩
$ tar -cvf <target_file> <source file/folder>

c代表compress; z代表gzip的压缩包; x代表extract; v代表显示过程信息; f代表后面接的是文件.

scp

# 下载
$ scp -i <pem file> <username>@<ip>:<remote/path> <local/path>

# 上传
$ scp -i <pem file> <local/path> <username>@<ip>:<remote/path> 

Suppress all logs

$ {{ commands }} >/dev/null 2>&1
# `>/dev/null` 代表把`stdout`输出到不存在的地方,`2>&1`代表把`stderr`输出到`stdout`

find

# Find a file under a directory
$ find ./dir -name "*.h"

# Delete the folders that does not meet name_pattern in the path depth of 1.
$ find { DIR } -mindepth 1 -maxdepth 1 -not -name '{ name_pattern }' -type d -exec rm -rf {} +

# For multiple patterns with `or`,
$ find { DIR } -mindepth 1 -maxdepth 1 \( -not -name "*.py" -o -name "*.html" \) -type d -exec rm -rf {} +

cut

TODO

alias

For example, I want to add alias for Linux WeChat app. Add following commands to the last line of file ~/.bashrc. (I have an NPM project for electronic-wechat project). alias wechat="npm start --prefix ~/Develop/WorkSpace/electronic-wechat"

Some useful alias:

alias untar='tar -zxvf '
alias ping5='ping -c 5'
alias www='python -m SimpleHTTPServer 8000'
alias ipe='curl ipinfo.io/ip'
alias ipi='ipconfig getifaddr en0'
alias c='clear'

wc

# Count the lines.
$ ... | wc -l
# Count the bytes.
$ ... | wc -c
# Count the characters.
$ ... | wc -m
# Count the words.
$ ... | wc -w

type

Get the type of a command.

$ type cd
cd is a shell builtin
$ type type
type is a shell builtin

disk/fs related

$ lsblk
$ df -h
$ du -sh
$ du -sh *
$ sudo resize2fs /dev/xvdf

date

$ yesterday=`TZ=Singapore date --date="-1 day" +%Y%m%d`
$ echo $yesterday # 20190117

kill a process by name

$ kill $(ps aux | grep '[k]ill_me.py' | awk '{print $2}')