bash shortcuts

tl;dr: bind common commands to shortcuts. save time. love life.

cost: $0 or $29 one time with Alfred Powerpack

read time: 15 minutes

I've bound my most commonly used bash snippets to shortcodes to use them more effectively. I prefer using Alfred to implement the snippet text expansion, as they will work in any field that accepts text. A downloadable .alfredsnippets file that includes all the below snippets can be found here

If you only want this functionality in your terminal (for free), you can add them as aliases in your bash_profile file instead (example below ⬇️)

# Add a environment key:val pair
echo 'export ENV_VAR=specific value' >> ~/.bash_profile
# Add a bash snippet alias
echo 'alias ;cd="cd ~/Dropbox/projects/specific/folder/pathing"\n' >> ~/.bash_profile
# Make sure to update your terminal session after
source ~/.bash_profile

(you can check the bash_profile at any time with)

cat ~/.bash_profile

Mac users can alternately use Settings -> Keyboards -> Shortcuts to bind shortcodes (Guide)


general

;genkey - generate a random string of characters (e.g. for a password)

LC_ALL=C tr -dc 'A-Za-z0-9' </dev/random | head -c 40 ; echo

;folders - map the current folder structure

ls -R | grep "^[.]/" | sed -e "s/:$//" -e "s/[^\/]*\//--/g" -e "s/^/   |/"

;history - export your bash shell history to .txt file

history > history_for_print.txt

;exit - exit Vim 😛

:wq


virtual env & dependencies

;venv - general a virtual environment (you can alternately use pipenv shell)

virtualenv venv && source venv/bin/activate

;pipv - install a specific version of a dependency (change pyyaml)

pip install --force-reinstall pyyaml==3.12

;listlibs - get a list of every installed library, ranked by size (SO)

pip3 list --format freeze|awk -F = {'print $1'}| xargs pip3 show | grep -E 'Location:|Name:' | cut -d ' ' -f 2 | paste -d ' ' - - | awk '{print $2 "/" tolower($1)}' | xargs du -sh 2> /dev/null|sort -h

;countpy - count Python Lines of Code (LoC)

wc -l $(git ls-files | grep '.*\.py')

;delpyc - delete cached python files (.pyc)

find . -name "*.pyc" -exec rm -rf {} \;

;format - reformat the local folder's contents with flake8 and black

black ./
flake8 ./

;timestamp - print the current time as a POSIX timestamp

python3
from datetime import datetime
print(int(datetime.now().timestamp()))

;jupyter - cd into jupyter folder and start jupyter notebook (change documents/swe/jupyter)

cd documents/swe/jupyter && jupyter notebook


github specific

one line git push (SO USEFUL) - (GH origin). Open your bash_profile

open -e ~/.bash_profile

and paste in this function:

function gacp() {
    git add .
    git commit -a -m "$*"
    git push origin master
}

(update your current session with source) then you can quickly and easily commit and push with

gacp testing one-line commit-push

;debugpush - push an empty Git commit (for debugging, redeploying, etc):

git add .
git commit --allow-empty -m "Intentionally empty debug push"
git push origin master

;gpr - push your local branch to a remote branch and prepare a pull request (change NEW_BRANCH_NAME)

git push origin master:NEW_BRANCH_NAME
# alternately, to any repo to which you have PR rights
git push git@github.com:USERNAME/REPO.git master:NEW_BRANCH_NAME

;greset - Go back one commit. (Docs on hard vs soft)

git reset --soft HEAD~1

;ginit - create a new repo and attach to a remote one

git init && git add . && git commit -m "initial commit" && git remote add origin git@github.com:alecbw/repo-name.git

;gitignore - pull the standard python .gitignore to your local directory

curl -sL https://www.gitignore.io/api/python > .gitignore
# optionally add things with
open -e .gitignore

;gauth - SSH to GitHub

ssh -vT git@github.com


Serverless.com specific

;slstd - run local tests and deploy Serverless stack (change serverless-1.yml and tests.test_handlers pathing)

python3 -m tests_folder.test_file && sls deploy --conceal --config "specific-serverless.yml" --stage prod

;slsgd - commit changes and deploy Serverless stack (change serverless-1.yml)

git add . && git commit -m "Automatic commit with sls deploy" && sls deploy --conceal --config "specific-serverless.yml" --stage prod

Note: you'll want to move this to a push to deploy model as your stack matures. I've enjoyed using CircleCI for that.

;slsil - locally test a given Lambda with hardcoded data (change the function and data and make as many variants as you want)

sls invoke local -f gsheet-read -d '{"Gsheet":"1RrgpAQx0Dz5gi-FOQVcictoTI5OZDoSdUvVNCteZSX4", "Tab":"Sheet1"}'


AWS specific

;awsaccount - set the Account ID as an env var

export AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)

;ec2desc - (change PROFILE)

aws ec2 describe-instances --profile PROFILE

;dydesc - get size, description of Dynamo table (change tableName) (case sensitive)

aws dynamodb describe-table --table-name tableName

;s3desc - get size, description of S3 bucket (change bucket-name)

aws s3api list-objects --bucket bucket-name --output json --query "[sum(Contents[].Size), length(Contents[])]"

;s3sync - download a S3 bucket's contents (change path/to/bucket-name)

aws s3 sync s3://path/to/bucket-name .

;s3ttl - check the Lifecycle Policies of a S3 bucket (change bucket-name)

aws s3api get-bucket-lifecycle-configuration  --bucket bucket-name

;s3newbucket - create a new bucket

aws s3api create-bucket --bucket bucket-name --region us-west-1 --create-bucket-configuration LocationConstraint=us-west-1

;checkstack - checks the status of your CloudFormation stack (in case it's stuck in Rollback hell) (change YOURSTACK)

aws cloudformation describe-stacks  --query 'Stacks[0].StackStatus' --output text --stack-name YOURSTACK


heroku specific

;hconfig - show Heroku config, incl env vars

heroku config

;hkill - restart a specific dyno

heroku restart worker.1

;hlog - stream heroku logs (change app-name)

heroku logs -a app-name --tail

;hdb - open a SSL connection to Heroku Postgres database (change app-name)

heroku pg:psql --app app-name

;hlocal - run localhost version of Heroku server (http://0.0.0.0:5000/)

heroku local web

;hmigratedb - run Heroku Django DB migration

heroku run python3 manage.py makemigrations
heroku run python3 manage.py migrate
heroku run python3 manage.py showmigrations


flask specific

;flrun - (change FlaskApp.py)

export FLASK_APP=FlaskApp.py && FLASK_APP=FlaskApp.py flask run

;fldebug - put Flask into DEBUG.

export FLASK_DEBUG=1


django specific

;djdebug - put Django into DEBUG. Note: this is not safe for production

export DEBUG_MODE=True && export heroku config:set DEBUG_MODE=True

;djlocal - run localhost version of server

python3 manage.py runserver

;migratedb - create or update db tables. Django will make a corresponding file in boards/migrationsdirectory.

python3 manage.py makemigrations
python3 manage.py migrate
python3 manage.py showmigrations


Postgres specific

;exportdb - export current table to CSV (change tableName)

\copy tableName TO 'OUTPUT_FILE_NAME.csv' DELIMITER ','


misc

;whois - generic WHOIS (change url.com)

whois $(dig +short url.com | head -1)

;catcsv - concatenate multiple CSVs in local folder. A more advanced version can be found here

cat *.csv > combined.csv

;countcsv - count the lines of a CSV without opening. Very helpful if it's above the million or so row limit (change your_file.csv)

cat your_file.csv  | wc -l

;headcsv - similarly, get the first n rows of a CSV w/o opening it

head -n 5 your_file.csv

;alltxt - change the filetype (by appending) every file in a folder SO

find . -type f -exec mv '{}' '{}'.txt \;


Thanks for reading. Questions or comments? 👉🏻 alec@contextify.io