Skip to content

Bash Scripts

kimschles edited this page Feb 26, 2019 · 4 revisions

Bash Scripting

Basics

  • Bash is the Bourne Again Shell

  • First line: #!/bin/bash or #!/usr/bin/env bash

  • Run file by adding ./ at the beginning

  • For example: ./say_hello.sh

Change a file to be executable

  1. Look at the file:
    • ls -l <filename.sh>
  2. If this is at the beginning of the file (-rw-r--r--), you need to change it to be executable
  3. Change the file permissions:
    • chmod 755 <filename.sh>

The shorthand 755 is often used for scripts as it allows you the owner to write or modify the script and for everyone to execute the script.

  1. A different way to make a file executatble
    • chmod +x <filename.sh>

A cron job is when you schedule a recurring task (when a script is run)

the $PATH variable is a set of folders where executable programs live.

Isolate the name of the directory you're in

DIRECTORY_NAME= pwd | xargs basename echo $DIRECTORY_NAME

${PWD##*/}

Regex, Find and Cut

  • Regex for exact match: ^pattern_here$
  • Find only directories or files: find dir_name -type d or find dir_name -type f
  • Find directories and exclude paths: find dir_name -type d -not -path '*/\*'

Common Safguards in a Shell Script

Bash Best Practices

  • Exit a script if part of it fails:
    • set -o errexit or set -e
  • Exit a script if a variable is use which has not been initialized
    • set -o nounset or set -u
  • Prevent piping from causing non-zero exit codes to be ignored
    • set -o pipefail

Comparison Operators

  • == *
  • !=
  • =~
    • Used when a regular expression is involved. The right side is considered an extended regular expression. If the left side matches, the operator returns 0, and 1 otherwise.

Exit Codes

  • success is 0
  • failure is anything other than 0
  • Show the exit code of the last process:
    • echo $?
  • Scripts should

Built-In Vairiables

  • run ./install.sh 1 2 3
    • $#: the length of the input (3)
    • $@: the input (1 2 3)
    • $?: was the last command successful? If yes, the result will be 0

OMG, why isn't this working?

  • try wrapping your command in $( )
    • it means 'evaluate this and use the result'
  • Example:
exitcode=$(curl -s -o /dev/null -w "%{http_code}" https://gitlab.com/stable-orbit/$REPO_NAME)

echo ${exitcode}

Stuff EJ told me

function clone_and_clean_repo {
    mkdir temp || true #prevents exit if the dir already exists
    cd temp
    git clone git@github.com:reactiveops/$REPO_NAME
    cd $REPO_NAME
    rm -rf ./* # rm -rf in a script can be dangerous. $(PWD) was removing the entire direcotry, `./*` removes all non-hidden files in the current directory leaving .git which is required for the next steps
    echo "# [deprecated] $REPO_NAME\nIf you would like this code, please go to https://gitlab.com/stable-orbit/$REPO_NAME)" > README.md
    push_changes
}
Clone this wiki locally