Bash Cheatsheet

I've gotten tired of googling the same things over and over again.

While loops

Note to self: If you find yourself doing this, you should probably stop and reevaluate why you're not using python. Also, this is obviously an infinite loop, and is probably not going to be especially helpful.

while [ $item = true ]; do echo 'bla'; done

SCP file between two remote hosts from your computer

This is useful if you have two aws instances, and want to transfer a file between them from your laptop.
scp -3 -i <pem file> user1@system_with_file:/file/to/xfer user2@system_that_needs_file:/file/to/xfer


Create sudo user non-interactively

Skip the prompts that come with creating a user typically, and give them sudoers privileges. Replace *username* with the user you want to create.

adduser --disabled-password --gecos "" *username*
touch /etc/sudoers.d/10_*username*
echo '*username* ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/10_*username*


Run function as another user

export -f <function_name>
su <user to run function as> -c "bash -c <function_name>"

Exit-on-error mode

Put this at the top of your bash script: set -e.
If a command returns a nonzero status, the shell will exit.


Regexing with grep

This will get the version of ruby from rvm:
rvm list | head -n 1 |grep -Po '\-(.*?)\s' | tail -c +2
The output from that command that it is parsing will look something like this: ruby-2.5.1 [ x86_64 ]

It will return 2.5.1.


Code Style

Function declarations:



Variable declaration:


Source filenames should be lowercase with underscores to separate words, i.e.