Command Line Interfaces

More of a reference for me than anyone else, but I use these shell commands quite frequently.

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]

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 660 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'

Create a new MySQL user and grant appropriate permissions

CREATE USER 'username'@'localhost' IDENTIFIED BY 'p4ssw0rd';
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, LOCK TABLES ON `username`.* TO 'username'@'localhost';
FLUSH PRIVILEGES;
SHOW GRANTS FOR 'USERNAME'@'localhost';

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

Preferred directory formatting

alias ls="ls -lBq --si --color=always --group-directories-first"
# -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?

# 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

function extract()
{
	if [ -f $1 ] ; then
		case $1 in
			*.tar.bz2) tar xvjf $1 ;;
			*.tar.gz) tar xvzf $1 ;;
			*.bz2) bunzip2 $1 ;;
			*.rar) unrar x $1 ;;
			*.gz) gunzip $1 ;;
			*.tar) tar xvf $1 ;;
			*.tbz2) tar xvjf $1 ;;
			*.tgz) tar xvzf $1 ;;
			*.zip) unzip $1 ;;
			*.Z) uncompress $1 ;;
			*.7z) 7z x $1 ;;
			*) echo "'$1' cannot be extracted via >extract<" ;;
		esac
	else
		echo "'$1' is not a valid file"
	fi
}

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/

Run a single command as another user

webuser() { sudo -H -u www-data bash -c "$1 $2 $3 $4"; }
alias web=webuser
web mkdir images // runs mkdir as www-data user

Find the 20 newest files in a directory

find . -printf "%T@ %Tx %TX %p\n" | sort -n -r | head -20

Quick scan for 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 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' {} +

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
}

List all files in a directory

list () {
	ls --format=single-column | egrep -v '\.'
}

Pipe ls search result to vi

vi $(ls | grep QUERY | awk '{ print $7 }')

Composer in place

# install specific package and version in current directory
composer create-project laravel/laravel . 5.0 --prefer-dist

Quick access to nginx site config

# quick access to nginx site config
config() {
    # If no param is passed, use current directory for search
    if [ -z "$1" ]
    then
        site=${PWD##*/}
    else
        site=$1
    fi

    # Location of config file
    configfile=/etc/nginx/sites-available/$site

    if [ ! -f $configfile ]; then
        echo "No config file found for site '"$site"'";
    else
        sudo vi $configfile;
    fi
}

Quick view for nginx site/main logs

log() {
    # was a parameter passed? If not...
    if [ -z "$1" ]

    # use current directory name as log name
    then
        log=${PWD##*/}-error.log

    # otherwise... manually send in directory name
    else

        # unless you want the main nginx log
        if [ "$1" == "main" ]
        then
            log=error.log

        # otherwise, pull the site you said
        else
            log=$1-error.log
        fi
    fi

    logfile=/var/log/nginx/$log

    if [ ! -f $logfile ]; then
        echo "No log file found at '"$logfile"'";
    else
        echo $logfile
        sudo tail $logfile -n 10;
    fi
}

Random server commands

sudo poweroff
sudo shutdown -r now // restart
sudo service nginx restart
sudo service apache2 restart

Show all users in MySQL

SELECT CONCAT(QUOTE(user),'@',QUOTE(host)) UserAccount FROM mysql.user;

List all users with possible shell access

tail /etc/passwd | grep '\/sh\|bash\|dash\|zsh\|ksh\|tmux\|screen'

Irritate the hell out of Linux fanboys

alias dos="PS1='C:\w/>'"
dos

Quality-of-life upgrades

alias x="exit"
alias sl="ls"
alias dir="ls"
alias cls="clear"
alias cd..="cd .."
alias please="sudo"
alias fucking="sudo"

In Windows

Autoload command aliases

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 Users\$USER directory matching the above (alias.cmd)

@echo off
doskey x=exit
doskey ls=dir
doskey killall=taskkill /F /IM $*

Leave a Comment