Personal Privacy

Login Advanced Search
     General TopicsSelf Hosted ServicesServer Setup

Bash Programming

Basics

Start the file using #!/bin/bash
Define a variable by simply using it without $. To use it later, add $ to the beginning.
To assign the outout of a command to a variable, put the command in parenthesis and add the $ to the beginning:

var1=$(command)

To read an input from user:

read -rp 'MESSAGE TO USER' var1

You can add a s switch to hide characters.
To get the current directory, use $PWD.
To get the current user, user $USER.

Logical Comparison

To see if two values are equal, simply use "$var1" = "$var2"
To implement a NOT, use !.
To implement an OR, use ||.
To implement an AND, use &&.

Conditional Statements

IF Statement

Syntax

if [ "condition1" ]; then
  do_this;
elif [ "condition2" ]; then
  do_that
else
  do_it
fi

For example, to compare the value of variable with a string use:

if [ "$var1" = "string1" ]; then
  ...
fi

To check is a variable is null use

if [ -z "$var1" ]; then
  do_if_variable_is_null
else
  do_if_not_null
fi

To check if a folder (or path) exist, use

if [ -d "LOCATION" ]; then
  ...
fi

For check if file exists, use -f instead.

SELECT Statement

Syntax

select opt in option1 option2 option3; do
  case $opt in
    option1)
      ...
      ;;
    option2)
      ...
      ;;
    *)
      default_action
  esac; done

TRY/CATCH Statement

Syntax:

#!/bin/bash

# Function to handle errors
handle_error() {
  local error_code=$?
  echo "Error occurred with exit code $error_code"
  # Add additional error handling logic here
  exit $error_code
}

# Set up trap to call the error handling function on any error
trap 'handle_error' ERR

# Your main script logic
main() {
  echo "Executing main script logic..."

  # Simulating an error
  command_that_might_fail
  echo "This line will not be reached if the previous command fails."

  echo "Script completed successfully."
}

# Call the main function
main

FUNCTION

To define a function, use

function FUN_NAME {
  ...
}

To pass variables to the function, call it using.

FUN_NAME "$var1" "$var2"

Then, inside the function, these variables can be used based on the order they are defined as

x=$1
y=$2

If you want to define a variable local for a function use

local var1=VAR

Normal variables defined inside the function are considered global variables.

Parsing Options from Command Line

To read options and their arguments from command line:

while getopts "s:rf:" option; do
  case "${option}" in
    s)
      commands_for_s_option # argument: "${OPTARG}"
      ;;
    r)
      commands_for_r_option
      ;;
    f)
      commands_for_f_option # argument: "${OPTARG}"
      ;;
    \?)
      echo "Error: Invalid option: -$OPTARG"
      exit 1
      ;;
  esac
done

In this example, options s and f must have an argument after the option.
However, r does not need an argument.

Buy me a coffe?!


Comments

No comments yet!
Add a new comment:

12