Bash Scripting Basics, Control Structures, Loops

๐Ÿ“Œ Bash Shell Scripting - Wikibooks

Basics

  • BASH shell scripts are essentially a series of bash commands that are stored in a file that can be executed by running the script.

hello-world.sh

#!/bin/bash

# This is a comment
echo "Hello world"
  • #!/bin/bash - the first line says the script should be run using bash

    • #! = shebang

  • # = pound/hash - used for comments

  • There are a few ways to execute the script:

bash hello-world.sh
	Hello world
# bash is the executable program

# To start the script without "bash" command, the script must be executable
chmod +x hello-world.sh
./hello-world.sh
	Hello world

executing-commands-example.sh

Control Structures

  • Conditionals allow the script to take different actions depending on some sort of state, referred to as if-then rules.

if-examples.sh

  • if statements.

    • The expression inside the brackets [[ ... ]] is evaluated and used to determine if the conditional code is executed.

    • If the expression evaluates to TRUE, the block (the code inside the IF statement) is executed.

    • If the expression evaluates to FALSE, BASH skips over all of the conditional code and starts execute after the "fi" keyword.

  • else statements

    • Code inside the else block is executed if the test returns FALSE.

  • elif statements (else-if)

    • If the first test in the if statement fails, the elif statement will be evaluated.

    • elif statements will be tested from top down.

    • the code block associated with the first TRUE evaluated test will be executed and the rest of the conditional will be skipped.

comparison-examples.sh

  • Examples of performing numerical and string comparisons.

case-example.sh

  • A case statement is essentially an if statement with multiple elif statements.

    • it uses a command line argument - $1

Loops

  • Loops allow to write code once and execute it multiple times.

Definite loops

  • know the number of loops (times it is executed) before the loop ever starts.

  • most common: for loop

Indefinite loops

  • unknown number of loops until the end (it depends on the user input for example).

  • most common: while loop

Infinite loops

  • loops that never end (whether by design or accident), != indefinite loops

loop-examples.sh

Examples

command-line-arguments-example.sh

  • Variables usage - $#, $*

generate-password.sh

  • This script generates a password by combining a specified number of words.

  • Each word is capitalized and separated by a separator character provided as a command line argument.

https://xkcd.com/936/

Last updated

Was this helpful?