-
Notifications
You must be signed in to change notification settings - Fork 12
Bash Scripts
kimschles edited this page Feb 26, 2019
·
4 revisions
-
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
- Look at the file:
ls -l <filename.sh>
- If this is at the beginning of the file (
-rw-r--r--
), you need to change it to be executable - Change the file permissions:
chmod 755 <filename.sh>
- 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.
DIRECTORY_NAME= pwd | xargs basename
echo $DIRECTORY_NAME
${PWD##*/}
- Regex for exact match:
^pattern_here$
- Find only directories or files:
find dir_name -type d
orfind dir_name -type f
- Find directories and exclude paths:
find dir_name -type d -not -path '*/\*'
- Exit a script if part of it fails:
-
set -o errexit
orset -e
-
- Exit a script if a variable is use which has not been initialized
-
set -o nounset
orset -u
-
- Prevent piping from causing non-zero exit codes to be ignored
set -o pipefail
-
==
* !=
-
=~
- 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.
- success is
0
- failure is anything other than
0
- Show the exit code of the last process:
echo $?
- Scripts should
- 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 be0
-
- 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}
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
}