Skip to content

Instantly share code, notes, and snippets.

@miron
Last active June 4, 2024 07:30
Show Gist options
  • Save miron/4997128 to your computer and use it in GitHub Desktop.
Save miron/4997128 to your computer and use it in GitHub Desktop.
cheatsheet
# grepable with inline comments.
# create alias: gh alias set cheat 'gist view 4997128'
# gh cheat | grep cheat -C 3, shows 3 lines before and after,
# Windows Powershell: gh cheat | Select-String cheat
bind -p | grep -v '^#\|self-insert\|^$' #list bash vim keybindings
shopt #shell options
bind -P #print keybindings
bash -x #print shellscript before executing, execute commands from file
help #brief summaries of builtin commands
fc #open last commandline in editor
kill -HUP $(ps -A -ostat,ppid | grep -e '[zZ]'| awk '{ print $2 }') #kill zombie processes
echo $0 #show if login shell or not, login shell has -bash
rm ./-somefileordir #remove file with hyphen
cd ./-somefileordir #change into dir with hyphen
type #type of command
type -a program #show path to all versions of program
export HISTTIMEFORMAT="%h/%d - %H:%M:%S " #shows date in historyfile
printf \t \n ... #formated print with tab and newline
grep -A 2 -B 3 foo README.txt # 2 lines before, 3 lines after
grep -C 3 foo README.txt # 3 lines before and after
xprop |grep WM_CLASS #get x11 window classname
echo "scale=2; x+y" | bc #calculations from cli, 2 decimals
echo "x*y" | bc -l #calculations from cli
sudo -s #stay in directory when sudo
man std::-->tab #c++ manpages
base64 #encode and decode using base64 representation
jq -r 'map(.Value | @base64d)' < file.json #decode base64 string of Value object
pdftotext my.pdf - | grep 'pattern' #grep through pdfs without writing txt file
yes foo > bar.txt #repeat some text (default is y) infinetly and save it to a file
strings #find the printable strings in a object, or other binary, file
mkfifo --mode=0666 /tmp/namedPipe #load SQL commands ...
gzip --stdout -d file.gz > /tmp/namedPipe #from gzipped file ...
LOAD DATA INFILE '/tmp/namedPipe' INTO TABLE tableName; #into database ...
java -version #java version
javac -version #java compiler version
ant -version #java make tool version
mvn #java project management tool
rcs #revision control system
tee #pipe to STDOUT and file
cal #display calendar
tidy #html parser
fmt #format text (TEX)
textutil #convert document-files
xpath #xml parser
xmllint #xml parser
locate -r "^\(.*/\)*header\.inc\.php$" #exact match
sqlite3 #sqlite cli interface ...
.databases #view databases ...
.open FILENAME #connect to database file ...
.tables #show tabes ...
.mode html #switch to html mode ...
.once FILENAME.html #query output to file ...
SELECT * FROM TABLE; # write content from table to FILENAME.html...
.quit #quit sqlite database ...
project.cj add overtone dep #overtone audio live coding
lein deps # ...
gibber #audiovisual live coding framework in javascript
xclip -sel clip < ~/.ssh/id_rsa.pub #copy from file to clipboard
sudo service start ssh start # start ssh daemon on WSL client and remotely connect to it
apt install <packet> # install gh in Kali, download deb: https://github.com/cli/cli/releases/latest
gcc -E -dM test.cpp #end after preprocessing, print defined macros
gcc -c file.cpp; objdump -d file.o #compile without linking, dissasemble object file
gcc -mno-red-zone file.cpp #turn off red zone for leaf functions
gcc -DSNIP #compile macro defined betwee in #if SNIP #endif
gcc -fno-exceptions #smaller binaries without exception handling
readelf -SW a.out #show elf tables like .eh_frame, exception handling framework
readelf --debug-dump=frames a.out #show table content
hexdump -C a.out #ELF string
readelf -hW a.out #ELF header
g++ file.cpp -v #compilation flags
readelf -lW a.out #ELF segments
gh gist create - # finish with ctrl-d. gist name is hash
gh gist create -d cheatsheet -f TITLE - # add new gist, name is TITLE, description is cheatsheet. finish wiht ctrl-d (2x)
https://developer.github.com/v4/explorer/ # Live GraphQL Github API explorer (create API calls for gh api graphql
gh gist list # neat colorfull list of your gits, use -L int to show more
gh gist edit 4997128 # get a neat menu and choose from the files in this gist to edit
git checkout -b BRANCH # create and checkout branch before pull request ...
echo "code" > code.txt; git add . # create file and stash ...
git commit -m "commit in branch before pull request" # ...
gh pr create --title "pull request" --body "comment" # select repo to push new branch ...
gh pr review --comment -b "comment" # reviews pull request and comments it
gh api repos/:owner/:repo/issues # will be replaced with values from repo, retrieve
gh issue create -R owner/repo # create issue in specified repository
# Don't Break the Chain productivity tracking with gh issue:
gh issue create -m <name> # Add issue to a milestone by name
# Automated in powershell for ($num =1 ; $num -le 365 ; $num++){ sleep 10 ; gh issue create -t 'learn python' -b ' ' -m python }
gh issue list --search 'sort:created-asc' # list issues in ascending order
gh issue close <number> # close issue
git update-git-for-windows # update to newest version on windows
git stash # save local modifications
git reset --hard 26b6d18 # hash before commit, destroys any local modifications!
git push --force (or git push -f) # all commits after reset will be deleted from history
git stash pop # reapply
git rm #remove file from repository
git svn clone ... ... # get the latest source from SVN ...
git checkout master # ...
git svn rebase # ...
git diff master # check differencies between modified and remote
git reset --hard HEAD^ # reset to previous
git revert HEAD # revert to previous, new commit
git revert --no-commit 0766c053..HEAD # revert to commit ...
git commit # and commit as HEAD ...
git grep -z --full-name -l '.' | xargs -0 sed -i -e 's/old-text/new-text/ig' # find and replace text in all files of a repository
git branch -m old_branch new_branch # Rename branch locally ...
git push origin :old_branch # Delete the old branch ...
git push --set-upstream origin new_branch # Push the new branch, set local branch to track the new remote ...
gitk # gui for git
# If you worked in wrong branch
git stash
git checkout main
git stash apply
bundle update github-pages #update to newest gems for github-pages inside repo ...
gem update github-pages # dito ...
bundle info --path minima #show where gem is located in project
https://api.github.com/emojis # markdown emojis :om:
git clone git@github.com:4997128.git #clone gist over ssh, add files like images, commit, push
## VIM ##
:grep -Rn TODO . "grep through all TODOs and open first occurence
:cn "switch to next occurence of TODO
:cp "switch to previous occurence of TODO
:make|!./%< "compile and execute programm
:vsplit | ctrl+w+v "split verticaly
:split | ctrl+w+s "split horizontaly
ctrl+w+J,r,L "switch splits
:so $MYVIMRC "reload .vimrc
:so % "if editing
:terminal "start terminal in vim
:vertical terminal "start terminal in vertical split
:term ./%< "run sourcecode in terminal
:%s/foo/bar/g "substitute
:ls "list buffers
:buffers "list buffers
:b "switch to buffer
:bnext "switch to buffer
:bprevious "switch to buffer
:buffer <number> "switch to buffer
:buffer <tab> "switch to buffer
ctrl-w s ctrl-w T "buffers to tabs
:tab ba "buffers to tabs
:bufdo tab split "buffers to tabs
gt "switch tabs
:w !sudo tee % "write to read only
:E rename files inside vim
:set invlist #invisible characters in vim
%s/ /^M/g #replace space with newline in vim (^M is Control-V Enter)
C-v I# ESC #comment block
C-o #paste in insert mode
:Ex[plore] #open current file's directory in vim
:noh #unhighlight search in vim
:term # ctrl-w N terminal scrollback buffer!
vim -c ':term ++curwin' #start vim as terminal in full screen
## VIM INSERT IN VSCODE AND PYCHARM ##
# Ctrl-o h move cursor left
# Ctrl-o l move cursor right
# Ctrl-o j move cursor down
# Ctrl-o k move cursor up
# Ctrl-h backspace/delete
# Ctrl-o x delete
# Ctrl-o R replace mode
# Ctrl-c or Esc exit replace mode
# Ctrl-t indent
# Ctrl-d unindent
# VIM NORMAL IN VSCODE
# f find forward, also works with df
# F find backward, also works with dF
# Ctrl-o, Ctrl-i jumplist (Ctrl-i brings you back)
# Ctrl-/ to quickly comment/uncomment in vscode
## VSCODE ##
# %% to create a notebook like cell in a python file in vscode, create new cell with Shift+Enter
# ctrl-1 focus editor
# ctrl=w j focus terminal (vim keybindings)
# "justMyCode": false, to step into external modules
# "cwd": "${fileDirname}", run debugger in directory of script
# "stopOnEntry": true, break at entry point of script
# Ctrl+Shift+P toggleVim temporaly disable Vim keybindings
# Ctrl+Shift+V render markdown, double click to switch back. disable vim keybindings first
# Ctrl+K V view rendered markdown side by side
## PYCHARM ##
Alt+4 # Focus Run window
Ctrl-0 (mapped) # Run File
Alt-= (mapped) # Focus Terminal
Alt-Shift-E # execute curent line in terminal
Ctrl+TAB # Focus and switch through open files...
## EMACS ##
C-s #incremental search
C-g #quit menu
C-x b #switch buffer
q #quit undo-tree
C-x C-b #list buffers
C-x 1 #close windows except cursor
TAB #select from completion
C-TAB #view list of M-x commands
C-x k #kill buffer
C-x o #switch to other window of buffers
M-b #vims *, beginning of word
C-s C-w #select word
C-w #further selection of word if underscore
C-s # ...
## BASH ##
ctrl-r #search history
ctrl-r #cycle
ctrl-g #quit search
arrow up/down #zoom in feh
ctrl+arrow up/down #pan in feh
#screen
^a | #split verticaly in screen
^a TAB #switch region screen
^a c #create session screen
^a " #choose session screen
^a X #close region screen
^a Q #close all regions beside actual one screen
^a [ #scroll buffer (vim style navigation) screen
^ l #clearscreen (cmd-k clears every region) screen
^b :set -g status off #disable statusbar in tmux
## MAC OS ##
cmd shift . #show hidden files in open dialog
NVAC (MCP79/MCP7A) #codename graphic card for nouveau driver
## Windows ##
# starting/switching windows with Win-<num> in the order pinned to your taskbar
# Win-` to open quake mode windows terminal
# Delete windows installed keyboard:
# https://superuser.com/questions/957552/how-to-delete-a-keyboard-layout-in-windows-10
# use US international keyboard for umlauts:
# " is dead key, use for ä,ü,ö,Ä,Ü,Ö,
# right Alt-s for ß and right Alt-5 for €
# Disable Zone Identifier
# gpedit.msc User Configuration/Administrative Templates/Windows Components/Attachment Manager
# "Do not preserve zone information in file attachments", Enabled
# cmd-shift-` to switch between app-windows (german keyboard)
ps -e | awk '/awk/ {next} {if(/ dd/) print "kill -INFO", $1}' | sh #get status of dd (also CTRL-T), or no pgrep (rescue disk)
# %wheel ALL=(ALL) NOPASSWD: ALL #sudo without password, uncomment ...
dscl . append /Groups/wheel GroupMembership USERNAME #this in etc/sudoers ...
vifs #safely edit fstab
iotop #harddisk I/O
iostat #I/O for disc and CPU
vm_stat #show mach virtual memory statistics
sudo killall -info mDNSResponder #retrieve internal state of mDNSResponder (/var/log/system.log starts at ---- BEGIN STATE LOG ----)
indent #indent and format C program source
otool -L /bin/ls #list dynamicaly linked libraries
kextunload -b org.virtualbox.kext.VBoxNetAdp #unload driver by bundlename
kextstat #list currently loaded drivers_
ls -d \*/ #list the directories in the current directory
sysctl net.inet.tcp.rfc1323 #TCP window scale option
nettop #network monitor
lsof -iP | grep -i "listen" #list listening ports
brew uses --installed #which packages depend on ...
brew uses --recursive #dependency tree
brew info $(brew list) |xargs -0 | grep -ZB2 Depends\ on #show packages with dependencies
brew leaves #packages without dependencies
brew cleanup #delete old versions
brew install --with-lua vim #vim with lua
ln -s /usr/local/bin/mvim /usr/local/bin/vim #start macvim without gui
brew install bash #enable autocd in macos ...
echo /usr/local/bin/bash >> /etc/shells # ...
chsh #change login shell #New shell: /usr/local/bin/bash ...
mysql.server start #start mysql
xcrun -find #show path of commands inside Xcode
/System/Library/Extensions/TMSafetyNet.kext/Helpers/bypass <cmd> #operate on files in Timemachine
cd /private/var/log/asl #speed up terminal in osx ...
ls \*.asl # ...
sudo rm !$ # ...
dscl #add users,... # ...
hdid #mount and manipulate local and remote .dmg images
hdiutil attach /Users/*/*.sparsebundle #mount a crypted user profile to /Volumes/*
hdiutil eject ... # ...
hdiutil compact ... #shrink after manipulation of files within the bundle ...
lsbom #list bill of materials of .pkg installers
mdfind #metadata search
mdfind -onlyin #specify searchdir
hostinfo #cpu and memory info
pkgutil --pkgs #list all installed packages (.pkg)
pkgutil --files PACKAGE #list files installed by package
vpnd #mac os VPN service daemon
dseditgroup #group record manipulation tool
say #text to speech
pbpaste #paste from clipboard
calendar /usr/share/calendar #calendars with events
pmset sleepnow #sleep from commandline
sips -g pixelWidth -g pixelHeight [image-file] #get picture dimensions
/Applications/Utilities/Network Utility.app/Contents/Resources/stroke #mac os built-in port scanner
defaults -currentHost write -globalDomain AppleFontSmoothing -int 2 #font smoothing
defaults write com.apple.finder AppleShowAllFiles TRUE #show hidden files in finder and timemachine ...
killall Finder # ...
curl ifconfig.me #show wan-ip /ua user agent, /all, ...
scp #reads also from .ssh/config
ssh -o "UserKnownHostsFile /dev/null" #don't write to .ssh/known_hosts ...
ssh-keygen -l -f /etc/ssh/ssh_host_ecdsa_key.pub #ECDSA key fingerprint
2>&1 | grep -v "^Warning: Permanently added" #for surpassing warning ...
vimdiff /etc/php5/cli/php.ini scp://root@remotehost:remoteport//etc/php5/cli/php.ini #vimdiff local vs remotefile
rsync #can also fetch mail via imap
curl -o /dev/null http://speedtest.wdc01.softlayer.com/downloads/test500.zip #command line speed test
sudo apachectl start #starts apache server
nc -zv servername 3306 #portscanner ...
#Connection to servername 3306 port [tcp/mysql] succeeded! ...
nmap -Pn -sS -p 80 -iR 0 --open #locate random webservers for browsing
fetchmail #fetch mail via imap
fetchmailconf #fetch mail via imap
netstat -tulpen #list listening ports
scp -P 401 root@servername:/* 'somefile' #don't do, copies rootdirectory to remotemachine
grep . /proc/sys/net/ipv4/tcp_* #tcp-settings
postfix #postfix mail server control program
iwlist wlan1 scan | grep Channel #scan interface and show busy channels
jnettop #network monitor
netstat #network monitor
iftop #network monitor
iperf #performance monitor
pppd #point to point protocol daemon
pacman -S #reinstall
pacman -Qm #list AUR packages and packages not from repository
pacman -Ss #search packages
cat /var/log/pacman.log | grep -i installed #last installed packages
cat /var/log/pacman.log | grep -iE 'installed|upgraded' #last upgraded packages
cat /var/log/pacman.log | grep -iE 'removed' #last removed packages
pacman -Ql package #list files of installed package
pacman -Qo FILENAME #from which local package is file
pacman -Fl FILENAME #list remote files
pacman -F FILENAME #from which remote package ...
pacman -Fy sync filedatabase #is file ...
pacman -Qi blackarch-wallpaper #show which packages depend on, installed
pacman -Sii blackarch-wallpaper #show which packages depend on, all
pacman -Qtd #dropped and orphaned packages
pacman -Rcuss #remove cascade, recursive, unneeded
pacman -Qkk #package integrity
pacman -S lostfiles #files not owned by arch
pacman -R $pkgname #remove (aur)packages
git clone REPO; makepkg; sudo pacman -U .pkg.tar.xz #install AUR package
makepkg -si #update AUR package which has daily builds
sudo pacman -Syu #update all packages
asp checkout linux #clone PKGBUILD repo ...
asp update #update repo ...
git pull # ...
makepkg --nobuild #download and extract sources only
Get-WmiObject Win32_DiskDrive #list available disks
Select-String cheat # powershell equivalent of grep
wsl --mount <DiskPath> --bare #make disk available to wsl2
$(ls dir/*.ext) # pass all files in dir as argument to cli-tools
# forwards traffic from port 2222 on host to sshd port 22 on wsl client
netsh interface portproxy add v4tov4 listenport=2222 listenaddress=0.0.0.0 connectport=22 connectaddress=localhost
netsh interface portproxy dump # shows configured port proxies
netsh interface portproxy delete v4tov4 listenport=2222 listenaddress=0.0.0.0 # deletes configured port proxies
netsh advfirewall firewall add rule name="WSL SSH" dir=in action=allow protocol=TCP localport=2222 # opens port for remote access
ssh user@192.168.0.1 -oPort=2222 # connects to your wsl machine
Set-PSReadLineOption -EditMode Vi # vim keybindings in powershell
Get-NetTCPConnection -State Listen,Established|
Select-Object LocalHost,LocalPort,RemoteHost,RemotePort,
@{'Name' = 'Process';'Expression'={(Get-Process -Id $_.OwningProcess).Path}} # Listening and Established connections with full process Path
cd \\wsl$\kali-linux # go to directory of wsl distro
kali run vi /mnt/c/Users/<user>/<file> # Edit file in powershell with vi in kali wsl
# Powershell in Linux
# In /etc/ssh/sshd_config:
# Subsystem powershell /usr/bin/pwsh --sshs -NoLogo -NoProfile
New-PSSession -hostname <IP address> -username <username> # In PS on Windows
Enter-PSSession <Sessionnumber> # Enter Session
Stop-Process -Id <ProcessId> # Close Session
Invoke-Command -Session(Get-PSSession <Sessionnumber>) -ScriptBlock { uname -a } # Remote Command
Expand-Archive <drive>\<path>\<file>.zip -DestinationPath <drive>\<path>\<directory> # unzip
docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_name_or_id #get IP address of container
systemctl start bluetooth #start bluetooth ...
systemctl status bluetooth #power on ...
bluetoothctl #scan on <cr> connect <cr> restart browser/app ...
systemctl list-unit-files --state enabled #enabled services, neat short and colorful
systemctl restart iwd.service #wlan not ready before systemd-networkd sometimes
script -fq /dev/null -c 'journalctl -f -p 4 -b' #failed at boot, color
xrandr --output DP-1 --mode 1920x1080 --rate 30.00 --above LVDS-1 #stop flickering of external monitor
sudo systemctl restart lxdm #restrart xserver
cat /sys/kernel/debug/dri/0/pstate #use pstate from cat ...
echo 0f > /sys/kernel/debug/dri/0/pstate #to boost graphic ...
dmesg --human #system message buffer, color, less
du -hs * | sort -rh | head -5 #biggest files
du -Sh | sort -rh | head -5 #biggest files, with subdirs
find -type f -exec du -Sh {} + | sort -rh | head -n 5 #biggest files including subdirs
sudo ip addr flush dev wlan0 #when starting dhclient -> RTNETLINK answers: File exists
hold ModKey + right click #resize "save as" dialoge in dwm
ctrl-shift-v #paste from firefox textfield to terminal
sysctl -a #get or set kernel parameters at runtime
file #filetype
ls -ldeo /Users/spartan/.ssh #show acl permissions
chmod -a# 0 /Users/spartan/.ssh #remove strange acls
ls -lO #list extended attributes
xattr #display and manipulate extended attributes
sudo gem update --system #update ruby gem
diff -rq folder1 folder2 #compare files in two directories
find . -path ./misc -prune -o -name '*.txt' -print #exclude directories in find (don't add the trailing slash to the directory)
whatis #short descriptions of system commands, words
apropos #short descriptions of system commands, strings
man -k #short descriptions of system commands, strings
whereis #locate programs
which #locate a program file in the user's path
ls *.txt #secure deletion ...
rm !$ # ...
dpkg-query -W -f='${Status} ${Version}\n' ... #check if package is installed or not
cat /etc/issue #show linux distro
lsb_release -a #show linux distro
debconf-show #show configuration
ps -p $$ #display current shell name
lsblk #list partition inside WSL
bpf_probe_read() #protects Linux from arbitrary memory
BPF_PROG_LOAD #verify and load a BPF program
@miron
Copy link
Author

miron commented Oct 1, 2020

Greppable with inline comments.
Create alias: gh alias set cheat 'gist view 4997128' to view with gh cheat.

Linux:
gh cheat | grep cheat -C 3
Views also the 3 entries before and after for multi line commands or groups of commands.

Windows Powershell:
gh cheat | Select-String cheat -Context 3
Views 3 entries before and after

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment