Skip to content

Instantly share code, notes, and snippets.

@ccdle12
Last active October 9, 2019 10:56
Show Gist options
  • Save ccdle12/cc77c4c31aee593d0cd18ebe8ec00c9d to your computer and use it in GitHub Desktop.
Save ccdle12/cc77c4c31aee593d0cd18ebe8ec00c9d to your computer and use it in GitHub Desktop.

Bash and Command Line

Arrays

Creating an array

node1_ip="172.25.0.102"
node2_ip="172.25.0.103"
node3_ip="172.25.0.104"

ips=($node1_ip, $node2_ip, $node3_ip)

Iterating over an array

ips=($node1_ip, $node2_ip, $node3_ip)
for ip in ${ips[*]}; do echo $ip; done

Command Outputs

Muting

When you nee to mute the output of a command.

  • command > /dev/null: redirects the output of stoud to null
  • 2>&1: redirects stderr to stdout
source venv/bin/activate > /dev/null 2>&1

Files

Appending to files

echo "something" >> some-file.txt

For Loop

Can be run on the command line and in a bash script.

for i in {1..3}; do <some-command>; done

Functions

function some_func() {...}

Returning a function

function some_func() {
  echo "Hello, World!"
}

If Statements

if [ some-statement ]; then
  do-stuff
fi

Check if folder exists

if [ -d "some-folder" ]; then
  do-stuff
fi

Folder doesn't exist:

if [ ! -d "some-folder" ]; then
  do-stuff
fi

Check if string in file

 if ! grep -q $1 docker-compose.yaml; then

Check if variable is empty

if [ -z $var]; then echo "var is empty" fi

Importing functions

Imports functions from another bash script.

. ./common.sh --source-only

Replace a String

Mac OSX:

sed -i "" "s/<old_string>/<replacement_string/<global>" <file_name>
sed -i "" "s/container_name: node/container_name: $1/g" docker-compose.yaml

Ubuntu:

sed -i "s/container_name: node/container_name: $1/g" docker-compose.yaml

Repeating Commands

More of a recipe than anything, but fi you are working on something and need to repeatedly use the same command.

Create an alias on the command line so it only lasts for the session.

alias r="python run-me.py"

Prompt

Automated input

some-command reset <<< "y"

or

echo "something" | ./some_script.sh

Sleep

sleep 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment