myscript

#!/bin/bash
#
# Print test of arguments.

echo number of args: $#
echo name of script: $0
echo all args: "$@"
echo last exit: $?

var1=3
var2=7

var3=$var1+$var2
echo $var3

var3=$(( $var1+$var2 ))
echo $var3

exit 0

directory_check

#!/bin/bash
#
# List contents of a subdirectory.

# Check for the correct number of arguments.
if [ $# -ne 2 ]; then
  echo "$0: requires 2 arguments: directory subdirectory" 1>&2
  exit 1
fi

if [ ! -d "$1" ]; then
  echo "$0: $1 is not a directory" 1>&2
  exit 1
fi

if [ ! -d "$1/$2" ]; then
  echo "$0: $2 is not a subdirectory of $1" 1>&2
  exit 1
fi

ls -l "$1/$2"
exit 0

counter

#!/bin/bash
#
# Loop to print numbers from 1 to 10.

# Use a while loop.
counter=1
while [ $counter -le 10 ]; do
   echo $counter
   ((counter++))
done

# Use a for loop.
echo "---"
for counter in {1..10}; do
  echo $counter
done

# Use a for loop (w/ seq).
echo "---"
for counter in $(seq 1 10); do
  echo $counter
done

# implicit exit 0
#!/bin/bash
#
# Loop to process command-line arguments.

# Use a for loop.
for arg in "$@"; do
  echo "$arg"
done

# Use a for loop (without quoting).
echo "---"
for arg in $@; do
  echo "$arg"
done

# Use a while loop.
echo "---"
while [ $# -gt 0 ]; do
   echo "$1"
   shift
done

# Implicit exit 0

file_iter

#!/bin/bash
#
# Iterate over files.

for file in $(ls); do
  if [ -f "$file" ]; then
    echo "$(wc -c < "$file") bytes in $file"
  fi
done

fibonacci

#!/bin/bash
#
# This script generates the Fibonacci sequence up to a given number.

# Check if an argument is provided, otherwise use default limit.
if [ $# -lt 1 ]; then
  limit=100
else
  limit=$1
fi

# Seed the sequence.
first=0
second=1

echo "Fibonacci sequence up to $limit:"
echo $first
echo $second

# Generate the Fibonacci sequence.
while [ $(( first + second )) -le $limit ]; do
  sum=$(( first + second ))
  echo $sum
  first=$second
  second=$sum
done

Bonus: hello_world

#!/bin/bash
#
# A basic hello world program.

hello_world () {
   echo "hello, world!"
}
hello_world

Bonus: function_params

#!/bin/bash
#
# Function to process input parameters.

my_function() {
  echo "Function Parameter 1: $1"
  echo "Function Parameter 2: $2"
}

# Check the number of command-line arguments
if [ $# -ne 2 ]; then
  echo "Usage: $0 <arg1> <arg2>"
  echo "Two arguments are required."
  exit 1
fi

# Call the function with the provided arguments
my_function "function_arg1" "function_arg2"

echo "Script Argument 1: $1"
echo "Script Argument 2: $2"

Bonus: variables

#!/bin/bash
#
# Local variables don't modify the scope outside of the function.

var1="A"
var2="B"

my_function () {
  local var1="C"
  var2="D"
  echo "Inside function: var1: $var1, var2: $var2"
}

echo "Before executing function: var1: $var1, var2: $var2"
my_function
echo "After executing function: var1: $var1, var2: $var2"