More of a reference for me than anyone else, but I use these commands quite frequently.
Shell_Commands::Simple
Useful shell aliases
# basic shell aliases alias x="exit" alias sl="ls" alias dir="ls" alias cls="clear" alias cd..="cd .." alias please="sudo" alias fucking="sudo" alias rl="echo '* shell profile reloaded!'; source ~/.bash_profile" alias :q="echo 'this isnt VIM, dummy...'; sleep 1; exit" # git aliases alias gs="git status" alias gl="git log --graph --pretty=format:'%Cred%h%Creset %Cgreen[%cr]%C(yellow)%d%Creset %s' --abbrev-commit" # path helpers export WEBDIR=~/code/sites alias webdir="cd $WEBDIR" # used in other places, hence the export alias nginx="cd /etc/nginx" # irritate Linux fanboys alias dos="PS1='C:\w/>'"; dos;
Allow ctrl+left and ctrl+right to jump words in the terminal
# place commands in ~/.inputrc "\e[1;5C": forward-word # ctrl+r_arrow "\e[1;5D": backward-word # ctrl+l_arrow "\e[1;6C": end-of-line # ctrl+shift+r_arrow "\e[1;6D": beginning-of-line # ctrl+shift+l_arrow
Set my PS1 prompt to something useful
PS1='\[\033]0;$MSYSTEM:${PWD//[^[:ascii:]]/?}\007\]\n\[\033[32m\]\u@\h \[\033[33m\]\w\[\033[0m\]\n> '
username@machine ~/file/path/goes/here
> (cursor)
> (cursor)
Move all visible AND hidden files to a new directory
# http://stackoverflow.com/questions/20192070/how-to-move-all-files-including-hidden-files-into-parent-directory-via mv /path/subfolder/{.,}* /path/
Generate a 12-character left-handed password
# password starts with lowercase alpha, excludes special characters that cause problems like $ and ! echo $(</dev/urandom tr -dc 'qwertasdfgzxcvb' | head -c 1)$(</dev/urandom tr -dc '12345@#%qwertQWERTasdfgASDFGzxcvbZXCVB' | head -c 11)
Run a single command as another user
# obviously change www-data to whatever user you need webuser() { sudo -H -u www-data bash -c "$1 $2 $3 $4"; } alias web=webuser # usage example web mkdir images
List all users with possible shell access
tail /etc/passwd | grep '\/sh\|bash\|dash\|zsh\|ksh\|tmux\|screen'
Find the 20 newest files in a directory
find . -printf "%T@ %Tx %TX %p\n" | sort -n -r | head -20
List all (only) filenames in a directory
list () { ls --format=single-column | egrep -v '\.' }
Quick scan for potentially nasty code
# http://www.gregfreeman.org/2013/how-to-tell-if-your-php-site-has-been-compromised/ find . -type f -name '*.php' | xargs egrep -i "(mail|fsockopen|pfsockopen|stream_socket_client|exec|system|passthru|eval|base64_) *\(" --color
Recursively replace text between two strings in all files
# Remove all text between /*STRING_1 and STRING_2*/ ... fucking hackers... find . -type f -exec sed -i -e 's/\/\*STRING_1.*STRING_2\*\///i' {} +
Pipe ls search result to vi
vi $(ls | grep QUERY | awk '{ print $7 }')
Jump back to the last-used directory
cd -
Deploy a composer package in place
# install specific package and version in current directory composer create-project laravel/laravel . 5.0 --prefer-dist
Random server power and service commands
sudo poweroff # shut 'er down! sudo shutdown -r now # restart the system sudo service nginx restart sudo service apache2 restart
List all currently configured sites in nginx
// From https://stackoverflow.com/a/46230868/3026221 nginx -T | sed -r -e 's/[ \t]*$//' -e 's/^[ \t]*//' -e 's/^#.*$//' -e 's/[ \t]*#.*$//' -e '/^$/d' | \ sed -e ':a;N;$!ba;s/\([^;\{\}]\)\n/\1 /g' | \ grep -P 'server_name[ \t]' | grep -v '\$' | grep '\.' | \ sed -r -e 's/(\S)[ \t]+(\S)/\1\n\2/g' -e 's/[\t ]//g' -e 's/;//' -e 's/server_name//' | \ sort | uniq | xargs -L1
Shell_Sequences::Complex
Install WordPress in about 10 seconds
# deploy the wordpress files ssh yourname@yourserver.com cd installdir rm * wget https://wordpress.org/latest.tar.gz tar -xvzf latest.tar.gz mv wordpress/{.,}* . rmdir wordpress rm latest.tar.gz mv wp-config.sample.php ../wp-config.php vi ../wp-config.php # set proper permissions sudo chown -R www-data:www-data * sudo find . -type f -exec chmod 664 {} + sudo find . -type d -exec chmod 755 {} + sudo chmod 600 wp-config.php
Add SSH key to remote host
# assuming you already have your local public key in ~/.ssh/id_rsa.pub # http://www.linuxproblem.org/art_9.html [remote] $ mkdir ~/.ssh [remote] $ touch ~/.ssh/authorized_keys [remote] $ chmod 700 ~/.ssh [remote] $ chmod 640 ~/.ssh/authorized [local] $ cat ~/.ssh/id_rsa.pub | ssh username@hostname 'cat >> ~/.ssh/authorized_keys'
I can never remember all the tar flags
# c - create a new archive # v - verbosely list files which are processed # z - filter the archive through gzip # f - following is the archive file name # x - extract files from archive # zip things up $ tar cvzf archive_name.tar.gz dirname/ # unzip everything $ tar xvfz archive_name.tar.gz
My preferred directory formatting
# -l : long format # -B : ignore entries ending with ~ (ignore backups) # -q : print ? instead of non-graphic characters # --si : Sizes in human-readable format ^1024 # --color=auto : color files # --group-directories-first : c'mon, really? alias ls="ls -lBq --si --color=always --group-directories-first" # don't have --group-directories-first? alias ls='ls -lBq --color=always --si | grep "^d" && ls -la | grep "^-" && ls -la | grep "^l"'
Handy extraction abstraction
#!/bin/bash # function Extract for common file formats # from https://github.com/xvoland/Extract/blob/master/extract.sh function extract { if [ -z "$1" ]; then # display usage if no parameters given echo "Usage: extract <path/file_name>.<zip|rar|bz2|gz|tar|tbz2|tgz|Z|7z|xz|ex|tar.bz2|tar.gz|tar.xz>" echo " extract <path/file_name_1.ext> [path/file_name_2.ext] [path/file_name_3.ext]" return 1 else for n in $@ do if [ -f "$n" ] ; then case "${n%,}" in *.tar.bz2|*.tar.gz|*.tar.xz|*.tbz2|*.tgz|*.txz|*.tar) tar xvf "$n" ;; *.lzma) unlzma ./"$n" ;; *.bz2) bunzip2 ./"$n" ;; *.rar) unrar x -ad ./"$n" ;; *.gz) gunzip ./"$n" ;; *.zip) unzip ./"$n" ;; *.z) uncompress ./"$n" ;; *.7z|*.arj|*.cab|*.chm|*.deb|*.dmg|*.iso|*.lzh|*.msi|*.rpm|*.udf|*.wim|*.xar) 7z x ./"$n" ;; *.xz) unxz ./"$n" ;; *.exe) cabextract ./"$n" ;; *) echo "extract: '$n' - unknown archive method" return 1 ;; esac else echo "'$n' - file does not exist" return 1 fi done fi }
Function: seek() – Scan directory for string instances
# useful for finding code snippets # search files recursively # replace all tab characters # replace multiple spaces # convert : to | # prefix line with > seek () { if [ -z "$1" ] then echo "USAGE: seek " else grep --color=always -r -i -n "$*" * | sed -e 's/\x09//g' | sed -e 's/ \+//g' | sed -e 's/\x1b\[K:/\x1b\[K | /g' | sed -e 's/^/ > /g' fi }
MySQL Commands
Create a new database and user with appropriate permissions for an application
# run as root appname=your-appname-here password=test1234secret mysql -e "CREATE DATABASE \`${appname}\` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci;" mysql -e "CREATE USER '${appname}'@'localhost' IDENTIFIED BY '${password}';" mysql -e "GRANT ALL ON \`${appname}\`.* TO '${appname}'@'localhost';" mysql -e "FLUSH PRIVILEGES;"
(old) Create DB and user from within MySQL
# create database CREATE DATABASE `appname`; # to create CREATE USER 'appname'@'localhost' IDENTIFIED BY 'p4ssw0rd'; GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, LOCK TABLES ON `appname`.* TO 'appname'@'localhost'; FLUSH PRIVILEGES; # to confirm SHOW GRANTS FOR 'appname'@'localhost';
Show all users in MySQL
SELECT CONCAT(QUOTE(user),'@',QUOTE(host)) UserAccount FROM mysql.user;
How big are the tables in my database?
SET @dbname = "my-database"; SELECT table_name AS "Table", ROUND(((data_length + index_length) / 1024 / 1024), 2) AS "Size (MB)" FROM information_schema.TABLES WHERE table_schema = @dbname ORDER BY (data_length + index_length) ASC;
How big are all my databases?
SELECT table_schema AS "Database", ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS "Size (MB)" FROM information_schema.TABLES WHERE table_schema NOT IN ("mysql", "sys", "information_schema", "performance_schema") GROUP BY table_schema;
Select Post and associated Postmeta in WP
SELECT p.ID, p.post_title, p.post_name, p.post_title, p.post_date, MAX(CASE WHEN pm1.meta_key = 'wprm_parent_post_id' then pm1.meta_value ELSE NULL END) as parent_id, MAX(CASE WHEN pm1.meta_key = 'wprm_video_metadata' then pm1.meta_value ELSE NULL END) as video_meta, MAX(CASE WHEN pm1.meta_key = 'wprm_video_embed' then pm1.meta_value ELSE NULL END) as video_embed, MAX(CASE WHEN pm1.meta_key = 'wprm_notes' then pm1.meta_value ELSE NULL END) as notes, MAX(CASE WHEN pm1.meta_key = '_thumbnail_id' then pm1.meta_value ELSE NULL END) as thumbnail FROM wp_kvhc_posts p LEFT JOIN wp_kvhc_postmeta pm1 ON ( pm1.post_id = p.ID) WHERE p.post_type = 'wprm_recipe' AND p.post_status = 'publish' GROUP BY p.ID, p.post_title ORDER BY p.ID DESC;
Windows Commands
Autoload command aliases from %USERPROFILE%/alias.cmd
Create a new registry entry in HKEY_CURRENT_USER/Software/Microsoft/Command Processor
Type: String Name: AutoRun Value: %USERPROFILE%\alias.cmd
Create a file in your %USERPROFILE% directory matching the above (alias.cmd)
@echo off doskey x=exit doskey ls=dir doskey killall=taskkill /F /IM $* # killall chrome.exe
JavaScript Snippets
Use jQuery to programatically create elements in a sensible way
// add our container div $("<div />", { "id": "wprm_frontend_links_container", "class": "wprm-admin-modal-field-container wprm-admin-modal-field-container-frontend_links" }).insertAfter($(".wprm-admin-modal-field-container-post_status")); $("<div />", { "class": "wprm-admin-modal-field-label", "text": "Frontend Links" }).appendTo($("#wprm_frontend_links_container")); $("<div />", { "id": "wprm_frontend_links", "class": "wprm-admin-modal-field", }).appendTo($("#wprm_frontend_links_container")); $("<a />", { "href": "/wprm_recipe/" + slug, "text": "WPRM Object", }).appendTo($("#wprm_frontend_links")); $("<a />", { "href": "/recipe/" + slug.replace("wprm-", ""), "text": "Post Wrapper", }).appendTo($("#wprm_frontend_links"));