Shell Scripts

Why shell script?

  • Automation

  • Monitoring and troubleshooting

  • Raise alarm and send notifications

  • etc.

Types of shell script

There are 2 types of CLI or shelss that are used in Unix-based OS like Linux and macOS

  • Bash (Bourne-Again-SHell)

  • Shell

To check which shell program is currently running on your OS

Scripting 101

Var

  • Case-sensitive, lower-case and underscores.

  • Start with $. e.g $my_variable

  • no space trailing allow

  • Include variable in a string in bash, using curly braces

Passing args

Input prompting

Operations (expr)

Double parentheses

Using double parenteses to perform arithmetic operations and comparation

Arithmetic operations

Comparison

Flow control

Condition

Loop

For loop

While loop

Case

Shebang

Shebang/Hashbang

Add the shebang line to the top of the script, so that even if the script is running from an unsupported shells, it will use the /bin/bash interpreter.

Exit code

Function

Using function to break up large script to smaller one. 1 function only performs a task.

Best practices

  • Design for re-usable, avoid duplicate code

  • Should not require to be edited before running

  • Use command line arguments to pass inputs.

  • Always return approriate exit codes in your script (0: success, >0: failure)

  • The shebang is placed at the 1st line of the script.

Resources

Bash cheat sheet
Very basic course to learn Shell scripting

Last updated