Linux Cheat Sheet

command cheatsheet

1
curl cheat.sh/command | bat

shell

for loop

1
2
3
4
colors=(red orange white "light gray")
for item in ${colors[@]}; do
    echo $item;
done

time

1
2
date "+%F %H:%M:%S.%N"
# 2023-01-25 23:55:00.152982295

set timezone

1
sudo timedatectl set-timezone America/Vancouver
1
sudo ln -s /usr/share/zoneinfo/America/Vancouver /etc/localtime

copy to clipboard

1
echo "copy" | xclip -set clip

sort

options

-k [n, m]选择区间
-tg分隔符
-M排序月份
-n以数值型进行排序
-h可读的数字(带单位)
-f忽略大小写

example

path

get script path

1
DIR=$(dirname $(readlink -f "$0"))

get invocation path

1
INV_DIR=$"PWD"

background

start a bg process and kill it

1
2
3
4
5
6
7
sleep 60 &

# Get last bg pid
pid=$!

# ...
kill $pid

sed

replace

1
2
sed -E -i 's/SEARCH_REGEX/REPLACEMENT/g' INPUTFILE
sed -E -i 's/Xft.dpi: [0-9]+/Xtf.dpi 144/g' ~/.Xresources
  • -i - Edit a file and don't write the output to stdout.
  • s - The substitute command.
  • /// - Delimiter character. It can be any character but usually the slash (/) character is used.
  • g - Global replacement flag. All occurrences are replaced if g provided.

awk

  • NOTE use '' instead of "" !
1
2
3
pactl get-sink-volume 0 | head -n1 | awk '{print $5}' | sed "s/%//g"

echo 'this is a test' | awk '{print $3}'

tmux

config

1
2
3
4
5
6
unbind C-b
set-option -g prefix M-Space
bind-key M-Space send-prefix

set -g default-terminal screen-256color
set-option -ga terminal-overrides ",*256col*:Tc"

options

  • start tmux new -s *SESSION_NAME*
  • attach tmux a -t *SESSION_NAME*
  • detach send-prefix d
  • create window send-prefix c
  • show sessions tmux list-sessions

jobs

list background process

  • jobs

environment

condition

中括号

单中括号 [ ]
  1. [ ] 两个符号左右都要有空格分隔
  2. 内部操作符与操作变量之间要有空格:如 [ "a" = "b" ]
  3. 字符串比较中,> < 需要写成> \< 进行转义
  4. [ ] 中字符串或者${}变量尽量使用""双引号扩住,以避免值未定义引用而出错
  5. [ ] 中可以使用 –a –o 进行逻辑运算
  6. [ ] 是 shell 内置命令
双中括号
  1. [[ ]] 两个符号左右都要有空格分隔
  2. [[ ]] 内部操作符与操作变量之间要有空格:如 [[ "a" = "b" ]]
  3. [[ ]] 字符串比较中,可以直接使用 > < 无需转义
  4. [[ ]] 中字符串或者${}变量尽量使用"" 双引号扩住,如未使用""会进行模式和元字符匹配
  5. [[ ]] 内部可以使用 && || 进行逻辑运算
  6. [[ ]] 是 bash keyword
example
equal
1
2
3
if [[ $randm == 1 ]] ; then
    echo $random == 1
fi
not equal
1
2
3
if [[ $randm != 1 ]] ; then
    echo $random != 1
fi

exist

environment variable
  • check if a environment variable is set
1
2
if [[ -z ${env} ]]; then
fi
command
  • check if a command exists
1
2
if ! command -v python &> /dev/null
fi

文件夹或文件

文件夹
1
2
if [ ! -d "folder" ] ; then
fi
文件
1
2
if [ ! -f "file" ] ; then
fi

find files

1
2
3
4
find ./fuzz-results/crashes -type f -name "id:$1*" -print0 | while read -d $'\0' file
do
    echo $file
done

xargs

多行转单行输入, 默认分隔符为换行

1
pacman -Q | grep -i "haskell" | xargs sudo pacman -S --noconfirm

placeholder

1
2
xargs -I {} mv dir1/{} dir2/{}
xargs -I '{}' mv dir1/'{}' dir2/'{}'

stream

symbolmeanings
0stdin
1stdout
2stderr
2>&1stderr to stdout
1>stdout redirect
2>stderr redirect
1>/dev/nullwrite to void

uniq

仅输出 unique 行

1
uniq -u

grep & rg

grep

no ignore

1
rg --no-ignore

zip

zip

compress
  • -q 不显示命令
  • -r 递归
  • -y 不解析 symbol link
1
zip -qry zip_file.zip file1 file2 dir1
decompress
1
unzip jacoco-0.8.7.zip -d jacoco
list
1
unzip -l zipfile.zip

tar

compress
1
tar -czf sample.tar.gz ./sample
decompress
1
tar -xzvf sample.tar.gz -C ./sample

git disable zsh status

1
2
git config --add oh-my-zsh.hide-status 1
git config --add oh-my-zsh.hide-dirty 1

zsh keybind

  • ^F ctrl-F
  • ^[F alt-F

list

1
bindkey -L

kernel

dependencies

1
sudo apt-get install libncurses-dev gawk flex bison openssl libssl-dev dkms libelf-dev libudev-dev libpci-dev libiberty-dev autoconf llvm

build

1
2
3
4
make menu_config
make -j$(nproc)
sudo make modules_install -j$(nproc)
sudo make install -j$(nproc)

get current kernel config

1
2
3
4
5
cat /boot/config

# or

zcat /proc/config.gz > config

kernel boot command

1
cat /proc/cmdline

network

iw

  • 格式
1
2
3
iw [ OPTIONS ] { help [ command ] | OBJECT COMMAND }
OBJECT := { dev | phy | reg }
OPTIONS := { --version | --debug }
  • 搜索
1
iw dev <devname> scan
  • 显示设备
1
iw dev
  • 显示设备信息
1
iw dev <devename> info
  • 显示连接信息
1
iw dev <devname> link
  • 连接
1
2
iw dev <devname> connect [-w] <SSID> [<freq in MHz>] [<bssid>] [key 0:abcde d:1:6162636465] [mfp:req/opt/no]
# Join the network with the given SSID (and frequency, BSSID).

iwd

connect

1
2
3
4
5
6
[iwd]# help
[iwd]# device list
[iwd]# station wlan0 scan
[iwd]# station wlan0 get-networks
[iwd]# station wlan0 connect SSID
[iwd]# station wlan0 show

Network Manager

  • 扫描
1
nmcli device wifi rescan
  • 显示
1
nmcli device wifi list
  • 连接
1
nmcli device wifi connect <SSID> password <password> [hidden yes]
  • connection up/down
1
nmcli connection up/down <connection>

ubcsecure

1
nmcli connection add type wifi con-name "ubcsecure" ifname wlan0 ssid "ubcsecure" -- wifi-sec.key-mgmt wpa-eap 802-1x.eap peap 802-1x.phase2-auth mschapv2 802-1x.identity "yayuwang" 802-1x.anonymous-identity "yayuwang" 802-1x.password "password..."

iwd configuration

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# /var/lib/iwd/ubcsecure.8021x
[Security]
EAP-Method=PEAP
EAP-Identity=username
EAP-PEAP-Phase2-Method=MSCHAPV2
EAP-PEAP-Phase2-Identity=username
EAP-PEAP-Phase2-Password=password

[Settings]
AutoConnect=true

ss

  • ss is the alternative of netstat
1
ss -tunpl

High DPI

Netease Music

1
2
3
#/opt/netease/netease-cloud-music/netease-cloud-music.bash

export QT_SCALE_FACTOR=2

ghidra

1
2
3
#/opt/ghidra/support/launch.properties

VMARGS_LINUX=-Dsun.java2d.uiScale=2

Wechat

1
2
#/opt/apps/com.qq.weixin.deepin/files/run.sh
export DEEPIN_WINE_SCALE=2.00

user management

add user

1
useradd miao

create home directory

1
useradd -m miao

add sudo access

1
usermod -aG sudo username

groups

list groups

1
groups $USER

sudo

list user's privilege

1
sudo -l

show login sessions

1
w

set passwd

1
passwd miao

ssh pem

  • 生成密钥
1
2
3
sudo su miao
cd ~/.ssh
ssh-keygen -t ed25519 -C "miao@mail.com"
  • 修改权限
1
2
3
cp ed25519.pub authorized_keys
chmod 600 authorized_keys
chmod 700 ~/.ssh
  • 拷贝密钥
1
scp root@10.105.250.92:/home/miao/.ssh/ed25519 ~/.ssh/

remove user

1
userdel -r username

change shell

1
chsh -s /usr/bin/zsh

ssh

sshd

1
2
3
4
Match User yayu
      X11Forwarding yes
      X11UseLocalhost no
      AllowTcpForwarding yes

ssh client

1
2
3
4
 Host github.com
    HostName github.com
    User git
    IdentityFile ~/.ssh/yayu

execute command

1
ssh leapx16 -t 'cd /home/yayu/ && pwd'

Xorg

names

xprop

wmctrl

1
wmctrl -x -l

touchpad

change scroll speed

1
2
3
4
5
6
7
8
Section "InputClass"
        Identifier "Enable natural scrolling by default"
        MatchIsTouchpad "on"
        MatchDevicePath "/dev/input/event*"
        MatchDriver "libinput"
        Option "Natural Scrolling" "on"
        Option "ScrollPixelDistance" "25"
EndSection

Archlinux

pacman

  • refresh pgp sudo pacman-key --refresh-keys

auto remove

  • sudo pacman -R $(pacman -Qdtq)

install deb

1
2
debtap *.deb
sudo pacman -U *.zst

install image

1
2
chmod +x ./app.AppImage
./app.AppImage

makepkg

install

  • -s, --syncdeps install dependencies
  • -i, --install install package
1
makepkg -si

yay

optiondescription
-Sinstall
-Sssearch the package
–mflags –skipintegskip validaty check
-Rremove
-RsRemove dependencies not required by other packages
-Scremove all cache
–overwrite <glob>Bypass file conflict checks and overwrite conflicting files
–editmenuedit pkgbuild before install
-Qlshow package contents
-Qoshow file owner
-Qishow package info

Bluetooth

install

1
yay -S bluez bluez-utils

pair

$ bluetoothctl

# power on
# default-agent
# scan on
[NEW] Device 00:12:34:56:78:90 Air Pods
# pair 00:12:34:56:78:90
# connect 00:12:34:56:78:90

airpods

1
2
# /etc/bluetooth/main.conf
ControllerMode = bredr

module

show loaded

1
lsmod

install/load

1
modprobe <module>

remove

1
2
modprobe -r <module>
rmmod <module>

nouveau

blacklist

1
2
# /etc/modprobe.d/nvidia.conf
blacklist nouveau

Remove kms from the HOOKS array in /etc/mkinitcpio.conf

regenerate the initramfs

1
mkinitcpio -p linux

keyboard layout

xmodmap

caps_lock -> control

1
2
3
4
5
# ~/.Xmodmap
clear lock
clear control
keycode 66 = Control_L
add control = Control_L Control_R

setxkbmap -option caps:ctrl_modifier

1
setxkbmap -option caps:ctrl_modifier

gpg

migrate

list keys

1
2
3
4
5
6
gpg --list-secret-keys --keyid-format LONG

sec   rsa4096/[your key] 2018-03-30 [SC]
      ABCDEFGHIJKLMNOPQRSTUVWXYZ
uid                 [ unknown] wyy (KEY NAME) <user@domain>
ssb   rsa4096/ABCDEFGHIJKL 2018-03-30 [E]

export

1
2
gpg --export -a [your key] > gpg-pub.asc
gpg --export-secret-keys -a [your key] > gpg-sc.asc

import

1
2
3
4
gpg --import gpg-pub.asc
gpg --import gpg-sc.asc
gpg --edit-key [your key]
trust [your key]

restart gpg-agent

1
sudo gpgconf --kill gpg-agent

restart

disk

format usb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
sudo fdisk /dev/sda

m # menu
p # print partition
d # delete partition
g # GPT partition table
n # new partition

sudo mkfs.ext4 -L Kingston -m 1 -b 4096 /dev/sda1
sudo mkfs.fat -F 32 -n Kingston /dev/sda1
sudo mkfs.exfat -n Kingston /dev/sda1

sudo dd if=/dev/zero of=/dev/sda1 bs=1M status=progress

install ISO

  1. ls -l /dev/disk/by-id/usb-*
  2. cp path/to/archlinux-version-x86_64.iso /dev/disk/by-id/usb-My_flash_drive

swap file

1
2
3
4
5
6
7
sudo fallocate -l 1G /swap
sudo dd if=/dev/zero of=/swap bs=1024 count=1048576
sudo chmod 600 /swap
sudo mkswap /swap
sudo swapon /swap
sudo swapon --show
genfstab / > /etc/fstab

misc

disable tab bell

1
set bell-style none

open terminal here

1
gsettings set org.cinnamon.desktop.default-applications.terminal exec kitty

font

utf-8 & locale

check

1
locale

set

1
2
3
# /etc/locale.conf

LANG=en_US.UTF-8

or

1
localectl set-locale LANG=en_US.UTF-8

show fonts

1
fc-list

systemd daemon

user

1
2
3
4
5
6
7
8
9
# ~/.config/systemd/user/xremap.service
[Unit]
Description=Xremap Daemon

[Service]
ExecStart=xremap /home/yayu/.config/xremap/config.yml

[Install]
WantedBy=default.target

system

1
2
3
4
5
6
7
8
9
# /etc/systemd/systemd/kmonad.service
[Unit]
Description=Kmonad Daemon

[Service]
ExecStart=/home/yayu/.local/bin/kmonad /home/yayu/.config/kmonad/kmonad.kbd

[Install]
WantedBy=default.target

journalctl

kernel log

1
journalctl -k

per service log

1
journalctl -u httpd

recent first / reverse

1
journalctl -r

CRLF

CR - Carriage Return

  • \r, 0x0D in hexadecimal, 13 in decimal
  • moves the cursor to the beginning of the line without advancing to the next line

LF - Line Feed

  • \n, 0x0A in hexadecimal, 10 in decimal
  • moves the cursor down to the next line without returning to the beginning of the line