Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
bash / shell cheatsheet

bash / shell Cheat Sheet

Using colors in shell output

RED='\033[0;31m'
NC='\033[0m' # No Color
printf "I ${RED}love${NC} Stack Overflow\n"

or with echo

echo -e "I ${RED}love${NC} Stack Overflow\n"

Color Codes:

Black        0;30     Dark Gray     1;30
Red          0;31     Light Red     1;31
Green        0;32     Light Green   1;32
Brown/Orange 0;33     Yellow        1;33
Blue         0;34     Light Blue    1;34
Purple       0;35     Light Purple  1;35
Cyan         0;36     Light Cyan    1;36
Light Gray   0;37     White         1;37

see ANSI Escape Codes

avoid entries in bash history

see http://unix.stackexchange.com/questions/115917/why-is-bash-not-storing-commands-that-start-with-spaces

export HISTCONTROL=ignoreboth 

start ssh-agent only once (in .profile on Mac)

SSH_ENV="$HOME/.ssh/environment"

function start_agent {
     echo "Initialising new SSH agent..."
     /usr/bin/ssh-agent | sed 's/^echo/#echo/' > "${SSH_ENV}"
     echo succeeded
     chmod 600 "${SSH_ENV}"
     . "${SSH_ENV}" > /dev/null
     /usr/bin/ssh-add;
}    

# Source SSH settings, if applicable

if [ -f "${SSH_ENV}" ]; then
     . "${SSH_ENV}" > /dev/null
     #ps ${SSH_AGENT_PID} doesn't work under cywgin
     ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
     start_agent;
 }
else
     start_agent;
fi

change directory to script's path

cd $(dirname $BASH_SOURCE[0])

get script's path

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

Provide proper usage information

#/ Usage: ./rollout.sh
usage() {
    grep '^#/' "$0" | cut -c4-
    exit 0
}
expr "$*" : ".*--help" > /dev/null && usage

clean up after script finishes

trap "rm -rf /tmp/concourse-deployment ca.pem" QUIT TERM EXIT INT

write heredoc into file

cat > ci/stub.yml << EOF
---
meta:
  ssh_key: (( file "/opt/workspace/concourse/concourse_rsa" ))
  target: tenant-deployer
EOF

dispatch commands to bash function

## copy-artifacts: copies compiled artifacts in preperation for Docker build
function task_copy_artifacts {
  prepare_client
  prepare_server
}

function task_usage {
    echo "Usage: $0"
    sed -n 's/^##//p' <$0 | column -t -s ':' |  sed -E $'s/^/\t/'
}

CMD=${1:-}
shift || true
RESOLVED_COMMAND=$(echo "task_"$CMD | sed 's/-/_/g')
if [ "$(LC_ALL=C type -t $RESOLVED_COMMAND)" == "function" ]; then
    pushd $(dirname "${BASH_SOURCE[0]}") >/dev/null
    $RESOLVED_COMMAND "$@"
else
    task_usage
fi

Check if variable is set

: "${VARIABLE_NAME:?'expected variable VARIABLE_NAME is not set'}"

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.