One-Liners

9 minute read

Bash

# Find files created today
$ find . -type f -daystart -ctime -1
# Find files create in the last 24 hours
$ find . -type f -ctime -1
# Delete empty directory
$ find . -type d -empty | xargs rmdir
# Find directories under $dir, with itself excluded
$ find $dir -mindepth 1 -type d
[ -d "$dir"  ] && echo "Directory $dir exists"
[ ! -d "$dir"  ] && echo "Directory $dir does not exist"
[[ -d $dir  ]] && echo "Directory $dir exists" || echo "Directory $dir does not exist"
# Extract audio
$ ffmpeg -i input-video.avi -vn -acodec copy output-audio.aac
$ ffmpeg -i video.mp4 -f mp3 -ab 192000 -vn music.mp3
# Rotate video
$ ffmpeg -i in.mov -metadata:s:v rotate="90" -codec copy out.mov
# Trim audio files
$ ffmpeg -i input.mp3 -ss 00:17:00 -acodec copy trim.mp3
$ ffmpeg -i input.mp3 -ss 00:00:00 -to 00:24:30 -c copy trim.mp3
# Add wav header to pcm files
$ ffmpeg -f s16le -ar 16k -ac 1 -i file.pcm file.wav
# Get parent pid
$ echo $PPID
$ cat /proc/$PPID/comm
$ cat /proc/$PPID/cmdline
# Install specific version of python package
$ pip install --user wlauto==3.1.1
$ pip install --user -v wlauto==3.1.1
# Get list of user installed packages using apt-mark
$ comm -23 <(apt-mark showmanual | sort -u) <(gzip -dc /var/log/installer/initial-status.gz | sed -n 's/^Package: //p' | sort -u)
# Get list of user installed packages using aptitude
$ comm -23 <(aptitude search '~i !~M' -F '%p' | sed "s/ *$//" | sort -u) <(gzip -dc /var/log/installer/initial-status.gz | sed -n 's/^Package: //p' | sort -u)
# Split large file
$ split -b 2G example.tar.bz2 example.tar.bz2.part
$ cat example.tar.bz2.part* >example.tar.bz2
# Make archive, exclude directory, .git and file
$ tar --exclude=".repo" --exclude-vcs --exclude='build.sh' -cvf /tmp/archive.tar ~/aosp
# Make archive, remove leading directory
$ tar -xf archive.tar --strip-components=1
# Search for line end with foo
$ grep 'foo$' -n file
# Search for line start with bar
$ grep '^bar' -n file
# Search for line with only one word
$ grep '^foo$' -n file
# Match zero or more white spaces
$ grep 'bar[ ]*$' -n file
# Use variable in grep, note the double quotes
$ foo=bar
$ grep "$foo[ ]*$" -n file
# Redirect top info to text file
$ top -b -d 1 p 1100 >>info.txt
# Play pcm audio file
$ aplay -f S16_LE -r 16000 *.pcm
# Move files to specified directory
$ find . -name *.jpg |xargs -i mv {} ~/moments
# Print line number, used for debug
$ echo $LINENO
# Power off ubuntu when process exits
$ sudo su -c 'while [[ -d /proc/6077  ]]; do sleep 10; done; poweroff'
# Connect to VPN
$ sudo openconnect ssl.linuxabc.com -b -u linuxabc
# Mount usbdisk
$ udiskctl mount -b /dev/sdb1
# Mount nfs
sudo mount -t nfs 192.168.1.89:/opt/nfsroot nfs/
# Mount iso
$ mount -t iso9660 ~/ubuntu-14.04.iso /media/cdrom/ -o loop
# Mount vfat partition
$ mount -t vfat /dev/sda6 /tmp/
# Install raspbian image to sd card
$ umount /dev/sdc1
$ sudo dd bs=4M if=2016-05-27-raspbian-jessie.img of=/dev/sdc
# Set VI Mode in Bash
set -o vi
# Set mac address
# ifconfig eth0 hw ether 001986060757
$ cscope -Rbkq
$ ctags -R
# Renaming files with whitespaces
$ rename 's/ /./g' *
# kill -9 `pidof adbd`
# List uvc camera supported resolution
$ uvcdynctrl -f to see supported resolution
# dmesg
# Show delta between two messages
dmesg -d
dmesg -t -d
# wait for new messages
dmesg -w
# Replace string
$ sed -i 's/find /find -L /g' build/core/Makefile
# Add prefix string to each line
$ sed -i -e 's/^/prefix/' file
# Extract dalvikvm related stuff to file
$ awk /"dalvikvm"/ logcat.txt > tmp.txt
# Get IP address
$ ifconfig eth0 | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p'
$ sudo update-alternatives --config java
# Line counting
# For git repo
$ git ls-files | xargs wc -l

# For non-vcs directory
$ wc -l $(find . -type f | egrep "\.(h|cc|c|cpp)")
# String length
$ string=123456790abcd
$ echo ${#string}
# Disk backup
$ rsync -rvlpogt /media/fdbai/ugreen/media/ /media/fdbai/Backup/media/
# Create user without prompt
$ adduser --disabled-password --gecos "" fdbai
$ Add user to sudo group
$ usermod -aG sudo fdbai
# Use proxy in command line
$ export http_proxy=http://127.0.0.1:1087;export https_proxy=http://127.0.0.1:1087;
# Rotate journal logs
$ sudo journalctl --rotate --vacuum-size=30M

Android

# Check apk debuggable
$ apkanalyzer manifest debuggable test.apk
# Get current Activity
dumpsys window windows | grep -E 'mCurrentFocus'
# Screen capture
screencap "/data/android-`date +%F-%H%M%S`.png"
# The level can be one of the following:
# HIDDEN
# RUNNING_MODERATE
# BACKGROUND
# RUNNING_LOW
# MODERATE
# RUNNING_CRITICAL
# COMPLETE
# am send-trim-memory  <pid> <level>
# Generate tombstone for specified pid
 debuggerd <pid>
# Reboot Android Device
setprop sys.powerctl reboot
svc power reboot
# Enter Recovery Mode
setprop sys.powerctl reboot,recovery
svc power reboot recovery
# Shutdown Android Device
setprop sys.powerctl shutdown
svc power shutdown

git

# Generate patches
$ git format-patch <sha> drivers/mmc/ include/linux/mmc/
$ git format-patch -1 <sha>
$ git format-patch -6 --cover-letter
# Undo git add
$ git reset file # undo one file
$ git reset      # undo all
# Discard changes
$ git reset --hard HEAD
$ git reset --hard HEAD^
$ git reset --hard HEAD^

$ git checkout -- <file or directory>
# Push to gerrit
$ git push origin HEAD:refs/for/master
# Push straight to the master branch
$ git push origin HEAD:refs/heads/master
# Find lost commit in git
$ git reflog
# Show just the current branch in Git
$ git rev-parse --abbrev-ref HEAD
$ git symbolic-ref --short HEAD

# for version 2.22 and above
$ git branch --show-current
# Fetch code without entering repo directory
$ git -C /usr/local/Homebrew/Library/Taps/homebrew/homebrew-cask fetch --unshallow
# Revert without prompt
$ git revert $hash --no-edit
# Ammend to add Change ID
$ git commit --amend --no-edit
# Remove commit from history
git reset --soft HEAD^
git push origin +master --force
# Check if there are files to commit
$ git ls-files --others --exclude-standard|wc -l
# Count git commits
$ git rev-list --all --count
$ git branch -r --contains $hash

Aliases

$ git config --global alias.st 'status -s'
$ git config --global alias.co 'checkout'
# Branch
$ git config --global alias.br branch
$ git config --global alias.contains 'branch --contains'
# Commit
$ git config --global alias.ci 'commit -v'
$ git config --global alias.cm 'commit -m'
$ git config --global alias.ca 'commit --amend'
$ git config --global alias.ac '!git add . && git commit -as'
$ git config --global alias.amend '!git add -u && git commit --amend --no-edit'
$ git config --global alias.this '!git init && git add . && git commit -m \"initial commit\"'
# Diff
$ git config --global alias.dc 'diff --cached'
$ git config --global alias.ds 'diff --stat'
# Cleanup
$ git config --global alias.cleanup '!git clean -fd && git checkout -- .'
# History
$ git config --global alias.last 'log -1 HEAD'
$ git config --global alias.ls 'log --pretty=oneline --decorate --graph --abbrev-commit --all'
$ git config --global alias.mine 'log --pretty=format:"%C(yellow)%h %C(green)%ad %C(red)%d %Creset%s" --decorate --date=short --author=Fudong'

$ git config --global alias.lrd 'log --pretty=format:"%C(yellow)%h %C(green)%>(12,trunc)%ad %C(dim cyan)%cn %C(red)%d %Creset%s" --decorate --date=relative'
$ git config --global alias.lsd 'log --pretty=format:"%C(yellow)%h %C(green)%ad %C(dim cyan)%cn%C(red)%d %Creset%s" --decorate --date=short'
$ git config --global alias.today 'log --pretty=format:"%C(yellow)%h %C(green)%ad %C(dim cyan)%cn %C(red)%d %Creset%s" --date=local --since=midnight'

$ git config --global alias.lrg 'log --pretty=format:"%C(yellow)%h %C(green)%>(12,trunc)%ad %C(dim cyan)%cn %C(red)%d %Creset%s" --decorate --date=relative --graph'
$ git config --global alias.lsg 'log --pretty=format:"%C(yellow)%h %C(green)%ad %C(dim cyan)%cn%C(red)%d %Creset%s" --decorate --date=short --graph'
# Remove already deleted files from git
$ git config --global alias.del '!git ls-files -z --deleted | xargs -0 git rm'
# Ignore a file
$ git config --global alias.ignore '!f() { echo $1 >> .gitignore; }; f'
# misc
$ git config --global alias.unstage 'reset HEAD --'
# Push changes to the current remote branch
$ git config --global alias.pc '!git push origin $(git rev-parse --abbrev-ref HEAD)'

$ git config --global alias.xx '!git reset $(git merge-base master $(git rev-parse --abbrev-ref HEAD))'
# See all git aliases
$ git config --global alias.alias 'config --get-regexp alias'

Gerrit

# push to gerrit
$ git push origin $branch_name:refs/for/$branch%r=foo@mail.com,r=bar@mail.com
$ alias gerrit='ssh -p 29418 admin@review.example.com gerrit'
# Create Project
$ gerrit create-project perftools.git --description "'Tools used for performance tuning'"
# List porjects
$ gerrit ls-projects
# Create branch
$ gerrit create-branch perftools oreo-release master
# Add reviewers alice and bob, but remove eve from change Iac6b2ac2.
$ gerrit set-reviewers -a alice@mail.com -a bob@mail.com -r eve@mail.com Iac6b2ac2
# Query Changes
$ gerrit query --format=JSON status:open project:perftools
# Review all the opened commit and submit for merging
$ gerrit review \
  --code-review +2 \
  --submit \
  --project perftools \
  $(git rev-list origin/master..HEAD)

gitea

# Create user repo
$ curl -X POST "http://$serverip/api/v1/user/repos?access_token=fd889d32aea95a6ba760a87dc19c44fe6100d406" -H "accept: application/json" -H "Content-Type: application/json" -d "{\"name\": \"blablabla\", \"private\": true}"

Digital Ocean

# List data center locations
$ doctl compute region list
# List distribution image
$ doctl compute image list-distribution --public
# Get SSH Key
$ doctl compute ssh-key list
# List plans
$ doctl compute size list
# Create droplet
$ doctl compute droplet create --region tor1 --image ubuntu-20-04-x64 --size s-1vcpu-1gb --ssh-keys 11:31:65:89:15:12:b8:cc:88:b8:73:32:81:6d:25:7a vps
# List droplet instances
$ doctl compute droplet list
$ doctl compute droplet list --format "ID,Name,PublicIPv4"
# Remove droplet
$ doctl compute droplet delete <DROPLET-ID>
$ doctl compute droplet delete -f <DROPLET-ID>

NextCloud

$ curl -u $username:$password -X MKCOL "https://$ipaddr/remote.php/dav/files/$username/Joplin" -k
# Install app
$ sudo nextcloud.occ app:install calendar

Docker

# Pull docker image
$ docker pull ubuntu:focal
# Run docker container
$ docker run -it ubuntu
# List running docker containers
$ docker ps
# List all docker containers
$ docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                      PORTS               NAMES
f4353d263b9b        ubuntu/focal:base   "/bin/bash"              11 months ago       Exited (255) 8 months ago                       quizzical_yonath
# List image
$ docker images
# Start docker
$ docker start -ai quizzical_yonath
$ docker start -ai f4353d263b9b

$ docker start quizzical_yonath
$ docker exec -u fdbai -w /home/fdbai -it quizzical_yonath zsh
$ docker exec -u fdbai -w /home/fdbai -it quizzical_yonath bash

bpftrace

# Listing probes
$ bpftrace -l 'tracepoint:syscalls:sys_enter_*'
# Hello world
$ bpftrace -e 'BEGIN { printf("hello world\n");  }'
# File opens
$ bpftrace -e 'tracepoint:syscalls:sys_enter_open { printf("%s %s\n", comm, str(args->filename));  }'
# Syscall counts by process
$ bpftrace -e 'tracepoint:raw_syscalls:sys_enter { @[comm] = count();  }'
# Distribution of read() bytes
$ bpftrace -e 'tracepoint:syscalls:sys_exit_read /pid == 18644/ { @bytes = hist(args->retval);  }'
# Kernel dynamic tracing of read() bytes
$ bpftrace -e 'kretprobe:vfs_read { @bytes = lhist(retval, 0, 2000, 200);  }'
# Timing read()s
$ bpftrace -e 'kprobe:vfs_read { @start[tid] = nsecs;  }
    kretprobe:vfs_read /@start[tid]/ { @ns[comm] = hist(nsecs - @start[tid]); delete(@start[tid]);  }'
# Count process-level events
$ bpftrace -e 'tracepoint:sched:sched* { @[name] = count();  } interval:s:5 { exit();  }'
# Profile on-CPU kernel stacks
$ bpftrace -e 'profile:hz:99 { @[stack] = count();  }'
# Scheduler tracing
$ bpftrace -e 'tracepoint:sched:sched_switch { @[stack] = count();  }'
# Block I/O tracing
$ bpftrace -e 'tracepoint:block:block_rq_complete { @ = hist(args->nr_sector * 512);  }'

Updated: