curriculum/challenges/english/blocks/review-bash-scripting/6724e417419c2f211bb41bfc.md
Bash scripting: Writing a sequence of Bash commands in a file, which you can then execute with Bash to run the contents of the file.
Shebang: The commented line at the beginning of a script (e.g., #!/bin/bash) that indicates what interpreter should be used for the script.
#!/bin/bash
Variable assignment: Instantiate variables using the syntax variable_name=value.
servers=("prod" "dev")
Variable creation rules: Create variables with VARIABLE_NAME=VALUE syntax. No spaces are allowed around the equal sign (=). Use double quotes if the value contains spaces.
NAME=John
MESSAGE="Hello World"
COUNT=5
TEXT="The next number is, "
Variable usage: Access variable values by placing $ in front of the variable name.
echo $NAME
echo "The message is: $MESSAGE"
Variable interpolation: Use $variable_name to access the value of a variable within strings and commands.
TEXT="The next number is, "
NUMBER=42
echo $TEXT B:$NUMBER
echo $TEXT I:$NUMBER
echo "Pulling $server"
rsync --archive --verbose $server:/etc/nginx/conf.d/server.conf configs/$server.conf
Variable scope: Shell scripts run from top to bottom, so variables can only be used below where they are created.
NAME="Alice"
echo $NAME
User input: Use read to accept input from users and store it in a variable.
read USERNAME
echo "Hello $USERNAME"
Comments: Add comments to your scripts using # followed by your comment text.
# and continue to the end of the line# This is a single-line comment
NAME="John" # Comment at end of line
Multi-line comments: Comment out blocks of code using colon and quotes.
: '
This is a multi-line comment
Everything between the quotes is ignored
Useful for debugging or documentation
'
Built-in commands and help:
help to see a list of built-in bash commandshelp <command> to get information about specific built-in commandsif) are built-ins and don't have man pageshelp function to see information about creating functionshelp
help if
help function
Finding command locations: Use which to locate where executables are installed.
which bash
which python
which ls
Manual pages: Use man to access detailed documentation for commands.
help instead)man echo
man ls
man bash
Help flags: Many commands support --help for quick help information.
ls --help
chmod --help
mv --help
Echo command options: The echo command supports various options:
-e option enables interpretation of backslash escapes\n creates a new lineecho -e "Line 1\nLine 2"
echo ""
echo -e "\n~~ Program Title ~~\n"
echo "Line 1\nLine 2"
Script arguments: Programs can accept arguments that are accessible using $ variables.
$* prints all arguments passed to the script$@ prints all arguments passed to the script as separate quoted strings$<number> accesses specific arguments by position (e.g., $1, $2, $3)echo $*
echo $@
echo $1
echo $2
[[ ]]Double bracket syntax: Use [[ ]] for conditional testing and pattern matching.
[[ $variable == "value" ]]
[[ $number -gt 10 ]]
[[ -f filename.txt ]]
String comparison operators: Compare strings using various operators within [[ ]].
== (equal): Tests if two strings are identical!= (not equal): Tests if two strings are different< (lexicographically less): String comparison in alphabetical order> (lexicographically greater): String comparison in alphabetical order[[ "apple" == "apple" ]]
[[ "apple" != "orange" ]]
[[ "apple" < "banana" ]]
[[ "zebra" > "apple" ]]
Numeric comparison operators: Compare numbers using specific numeric operators.
-eq (equal): Numeric equality comparison-ne (not equal): Numeric inequality comparison-lt (less than): Numeric less than comparison-le (less than or equal): Numeric less than or equal comparison-gt (greater than): Numeric greater than comparison-ge (greater than or equal): Numeric greater than or equal comparison[[ $number -eq 5 ]]
[[ $count -ne 0 ]]
[[ $age -ge 18 ]]
[[ $score -lt 100 ]]
Logical operators: Combine multiple conditions using logical operators.
&& (and): Both conditions must be true|| (or): At least one condition must be true! (not): Negates the condition (makes true false, false true)[[ $age -ge 18 && $age -le 65 ]]
[[ $name == "John" || $name == "Jane" ]]
[[ ! -f missing_file.txt ]]
File test operators: Test file properties and existence.
-e file: True if file exists-f file: True if file exists and is a regular file-d file: True if file exists and is a directory-r file: True if file exists and is readable-w file: True if file exists and is writable-x file: True if file exists and is executable-s file: True if file exists and has size greater than zero[[ -e /path/to/file ]]
[[ -f script.sh ]]
[[ -d /home/user ]]
[[ -x program ]]
Pattern matching with =~: Use regular expressions for advanced pattern matching.
=~ operator enables regex pattern matching[[ "hello123" =~ [0-9]+ ]]
[[ "[email protected]" =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]
[[ "filename.txt" =~ \.txt$ ]]
Variable existence testing: Check if variables are set or empty.
[[ ! $variable ]][[ ! $undefined_var ]]
(( ))Arithmetic evaluation: Use (( )) for mathematical calculations and numeric comparisons.
$ prefix inside double parentheses(( result = 10 + 5 ))
(( count++ ))
(( total += value ))
Arithmetic operators: Mathematical operators available in (( )).
+ (addition): Add two numbers- (subtraction): Subtract second number from first* (multiplication): Multiply two numbers/ (division): Divide first number by second (integer division)% (modulo): Remainder after division** (exponentiation): Raise first number to power of second(( sum = a + b ))
(( diff = x - y ))
(( product = width * height ))
(( remainder = num % 10 ))
(( power = base ** exponent ))
Assignment operators: Modify variables using arithmetic assignment operators.
= (assignment): Assign value to variable+= (add and assign): Add value to variable-= (subtract and assign): Subtract value from variable*= (multiply and assign): Multiply variable by value/= (divide and assign): Divide variable by value%= (modulo and assign): Set variable to remainder(( counter = 0 ))
(( counter += 5 ))
(( total -= cost ))
(( area *= 2 ))
(( value /= 3 ))
Increment and decrement operators: Modify variables by one.
++variable (pre-increment): Increment before usevariable++ (post-increment): Increment after use--variable (pre-decrement): Decrement before usevariable-- (post-decrement): Decrement after use(( ++counter ))
(( index++ ))
(( --remaining ))
(( attempts-- ))
Comparison operators: Compare numbers using arithmetic comparison.
== (equal): Numbers are equal!= (not equal): Numbers are not equal< (less than): First number is less than second<= (less than or equal): First number is less than or equal to second> (greater than): First number is greater than second>= (greater than or equal): First number is greater than or equal to second(( age >= 18 ))
(( score < 100 ))
(( count == 0 ))
(( temperature > freezing ))
Logical operators: Combine arithmetic conditions.
&& (and): Both conditions must be true|| (or): At least one condition must be true! (not): Negates the condition(( age >= 18 && age <= 65 ))
(( score >= 90 || extra_credit > 0 ))
(( !(count == 0) ))
Bitwise operators: Perform bit-level operations on integers.
& (bitwise AND): AND operation on each bit| (bitwise OR): OR operation on each bit^ (bitwise XOR): XOR operation on each bit~ (bitwise NOT): Invert all bits<< (left shift): Shift bits to the left>> (right shift): Shift bits to the right(( result = a & b ))
(( flags |= new_flag ))
(( shifted = value << 2 ))
Conditional (ternary) operator: Use condition ? true_value : false_value syntax.
(( result = (score >= 60) ? 1 : 0 ))
(( max = (a > b) ? a : b ))
(( sign = (num >= 0) ? 1 : -1 ))
Command substitution with arithmetic: Use $(( )) to capture arithmetic results.
result=$(( 10 + 5 ))
echo "The answer is $(( a * b ))"
array_index=$(( RANDOM % array_length ))
Conditional statements: Use if statements to execute code based on conditions.
if [[ CONDITION ]] then STATEMENTS fiif [[ CONDITION ]] then STATEMENTS elif [[ CONDITION ]] then STATEMENTS else STATEMENTS fi[[ ]] and (( )) expressions for different types of conditions(( ... )) and double brackets [[ ... ]] in same conditional chainif (( NUMBER <= 15 ))
then
echo "B:$NUMBER"
elif [[ $NUMBER -le 30 ]]
then
echo "I:$NUMBER"
elif (( NUMBER < 46 ))
then
echo "N:$NUMBER"
elif [[ $NUMBER -lt 61 ]]
then
echo "G:$NUMBER"
else
echo "O:$NUMBER"
fi
Command separation: Use semicolon (;) to run multiple commands on a single line.
[[ 4 -ge 5 ]]; echo $?
ls -l; echo "Done"
Exit status: Every command has an exit status that indicates success or failure.
$?0 means success (true/no errors)127 (command not found), 1 (general error)echo $?
[[ 4 -le 5 ]]; echo $?
ls; echo $?
bad_command; echo $?
Subshells and command substitution: Different uses of parentheses for execution contexts.
( ... ) create a subshell$( ... ) performs command substitution( cd /tmp; echo "Current dir: $(pwd)" )
current_date=$(date)
file_count=$(ls | wc -l)
echo "Today is $current_date"
echo "Found $file_count files"
Sleep command: Pause script execution for a specified number of seconds.
sleep 3
sleep 0.5
sleep 1
While loops: Execute code repeatedly while a condition is true.
while [[ CONDITION ]] do STATEMENTS doneI=5
while [[ $I -ge 0 ]]
do
echo $I
(( I-- ))
sleep 1
done
Until loops: Execute code repeatedly until a condition becomes true.
until [[ CONDITION ]] do STATEMENTS doneuntil [[ $QUESTION =~ \?$ ]]
do
echo "Please enter a question ending with ?"
read QUESTION
done
until [[ $QUESTION =~ \?$ ]]
do
GET_FORTUNE again
done
For loops: Iterate through arrays or lists using for loops with do and done to define the loop's logical block.
for server in "${servers[@]}"
do
echo "Processing $server"
done
for (( i = 1; i <= 5; i++ ))
do
echo "Number: $i"
done
for (( i = 5; i >= 1; i-- ))
do
echo "Countdown: $i"
done
for i in {1..5}
do
echo "Count: $i"
done
Arrays: Store multiple values in a single variable.
ARRAY=("value1" "value2" "value3")${ARRAY[0]}, ${ARRAY[1]}${ARRAY[@]} or ${ARRAY[*]}RESPONSES=("Yes" "No" "Maybe" "Ask again later")
echo ${RESPONSES[0]} # Yes
echo ${RESPONSES[1]} # No
echo ${RESPONSES[5]} # Index 5 doesn't exist; empty string
echo ${RESPONSES[@]} # Yes No Maybe Ask again later
echo ${RESPONSES[*]} # Yes No Maybe Ask again later
Array inspection with declare: Use declare -p to view array details.
-a flagARR=("a" "b" "c")
declare -p ARR # ARR=([0]="a" [1]="b" [2]="c")
Array expansion: Use "${array_name[@]}" syntax to expand an array into individual elements.
for server in "${servers[@]}"
Functions: Create reusable blocks of code.
FUNCTION_NAME() { STATEMENTS }$1, $2, etc.GET_FORTUNE() {
echo "Ask a question:"
read QUESTION
}
GET_FORTUNE
Function arguments: Functions can accept arguments just like scripts.
$1, $2, etc.GET_FORTUNE() {
if [[ ! $1 ]]
then
echo "Ask a yes or no question:"
else
echo "Try again. Make sure it ends with a question mark:"
fi
read QUESTION
}
GET_FORTUNE
GET_FORTUNE again
Random numbers: Generate random values using the $RANDOM variable.
$RANDOM generates numbers between 0 and 32767$RANDOM % 75$(( RANDOM % 75 + 1 ))$(( ... )) syntax for calculations with $RANDOMNUMBER=$(( RANDOM % 6 ))
DICE=$(( RANDOM % 6 + 1 ))
BINGO=$(( RANDOM % 75 + 1 ))
echo $(( RANDOM % 10 ))
Random array access: Use random numbers to access array elements randomly.
RESPONSES=("Yes" "No" "Maybe" "Outlook good" "Don't count on it" "Ask again later")
N=$(( RANDOM % 6 ))
echo ${RESPONSES[$N]}
Modulo operator: Use % to get the remainder of division operations.
$RANDOM to create bounded random valuesRANDOM % n gives numbers from 0 to n-1echo $(( 15 % 4 ))
echo $(( RANDOM % 100 ))
echo $(( RANDOM % 10 + 1 ))
Environment variables: Predefined variables available in the shell environment.
$RANDOM: Generates random numbers between 0 and 32767$LANG: System language setting$HOME: User's home directory path$PATH: Directories searched for executable commandsprintenv or declare -pecho $RANDOM
echo $HOME
echo $LANG
printenv
Variable inspection: Use declare to view and work with variables.
declare -p: Print all variables and their valuesdeclare -p VARIABLE: Print specific variable detailsdeclare -p
declare -p RANDOM
declare -p MY_ARRAY
Command types: Different categories of commands available in bash.
echo, read, if)ls, sleep, bash)then, do, done)type <command> to see what type a command istype echo
type ls
type if
type ./script.sh
File creation: Use touch to create new empty files.
touch script.sh
touch bingo.sh
touch filename.txt
sh scriptname.sh: Run with the sh shell interpreter.bash scriptname.sh: Run with the bash shell interpreter../scriptname.sh: Execute directly (requires executable permissions).sh questionnaire.sh
bash questionnaire.sh
./questionnaire.sh
Permission denied error: When using ./scriptname.sh, you may get "permission denied" if the file lacks executable permissions.
Checking permissions: Use ls -l to view file permissions.
ls -l questionnaire.sh
Permission format: The output shows permissions as -rw-r--r-- where:
-): File type (- for regular file, d for directory)r = read, w = write, x = executeAdding executable permissions: Use chmod +x to give executable permissions to everyone.
chmod +x questionnaire.sh
Script organization: Best practices for structuring bash scripts.
#!/bin/bash)#!/bin/bash
NAME="value"
ARRAY=("item1" "item2")
my_function() {
echo "Function code here"
}
my_function
echo "Script complete"
Sequential script execution: Create master scripts that run multiple programs in sequence.
#!/bin/bash
./setup.sh
./interactive.sh
./processing.sh
./cleanup.sh
Review the Bash Scripting topics and concepts.