DevOps

The Ultimate Bash Scripting Guide: From Basics to Advanced Shell Scripting

Bash scripting is a powerful way to automate tasks and manage systems in Unix/Linux environments

Creating your first script:

#!/bin/bash
echo "Hello, World!"

Making scripts executable:

chmod +x script.sh

Running scripts: ./script.sh

 

1. Basic Commands & File System Navigation:

  • pwd: Print working directory.

  • ls: List directory contents.

  • cd: Change directory.

  • mkdir: Create directory.

  • cp: Copy files/directories.

  • mv: Move/rename files/directories.

    • mv old_filename new_filename
    • mv report.txt final_report.txt
    • mv /home/user/oldname.txt /home/user/newname.txt
       
  • rm, rmdir: Remove files/directories.

    • rm -r folder_name
    • rmdir directory_name
    • rm -rf folder_name
    • -r : recursive (deletes subdirectories and files inside)
    • -f :force (ignores nonexistent files and never asks for confirmation)

       

  • cat, less, more: View file contents.

2. Variables and Data Types

name="Amrit"
echo "Hello, $name"

_arg_install=       # Unset/empty variable
_arg_wsl="off"
_arg_publish=()    # Declares an empty array

_arg_publish=()  

This defines an empty array, which can be later filled like:

_arg_publish+=("pkg1")
_arg_publish+=("pkg2")
# this will append the element
_arg_publish=("pkg1")
# will will override the array
# you can write string directly as
_arg_publish=(pkg3)

Access:

echo "${_arg_publish[@]}"   # All elements
echo "${_arg_publish[0]}"   # First element

 

Special Variables: $0 (script name), $1, $2 (positional parameters), $# (number of arguments), $? (exit status of last command).

Read user input:

read -p "Enter your name: " name

Redirection:

  • >: Redirect standard output to a file (overwrites).

  • >>: Redirect standard output to a file (appends).

  • <: Redirect standard input from a file.

  • 2>: Redirect standard error.

  • &>: Redirect both standard output and standard error.

3. Conditional Statements:

  • if statements

if [ "$name" == "Amrit" ]; then
  echo "Welcome!"
else
  echo "Access denied"
fi

Operators: -eq (equal), -ne (not equal), -gt (greater than), -lt (less than), -f (file exists), -d (directory exists).

  • case statement

    case $variable in
        pattern1)
            # commands
            ;;
        pattern2)
            # commands
            ;;
        *)
            # default commands
            ;;
    esac
  • Loop 

    • for, while, until

for loop.

    for item in list; do
        # commands
    done

while loop: 

    while [ condition ]; do
        # commands
    done
for i in {1..5}
do
  echo "Count: $i"
done

5. Arithmetic Operations

a=5
b=3
let sum=a+b
echo $sum

Or use $(( )):

sum=$((a + b))

6. Functions

Definition.

    function_name() {
        # commands
    }
  • Calling: function_name

greet() {
  echo "Hello, $1!"
}

greet "Amrit"

7. Handling Files

  • Reading and writing files
  • Using loops to read line-by-line
while read line; do
  echo "$line"
done < file.txt

8. Script Arguments and Flags

When you run a Bash script, you can pass values (arguments) to it from the command line. These values are accessible inside the script using special variables like $1, $2, $@, etc.

echo "Script name: $0"
echo "First argument: $1"
echo "All arguments: $@"
VariableDescription
$0Name of the script
$1First argument
$2Second argument
$@All arguments (as separate strings)
$*All arguments (as one string)
$#Number of arguments

Additional commands:

1. bin_dir=$(dirname "$0")

dirname command returns the directory portion of a path.

abc=$(dirname /home/amrit/scripts/myscript.sh)
# Output: /home/amrit/scripts

2.app_name=$(basename $PWD)

This is a command-line utility that strips the directory path and returns just the last part (the folder or file name).

basename /home/amrit/projects/myapp
# Output: myapp

 

Flags / Options (Advanced Argument Parsing)

Flags are like --help, -v, -f filename, etc., that control how your script behaves.

There are two common tools in Bash for parsing flags:

  1. getopts (for short options: -f)
  2. getopt (for long options: --file)

Using getopts (for short options like -f)

#!/bin/bash

while getopts "f:v" opt; do
  case $opt in
    f)
      echo "File: $OPTARG"
      ;;
    v)
      echo "Verbose mode ON"
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      ;;
  esac
done

getopts Explained:

  • "f:v" means:
    • f expects a value (-f filename)
    • v is a flag (no value)
  • OPTARG holds the argument passed to the option.

Run script:

./script.sh -f myfile.txt -v

Output:

File: myfile.txt
Verbose mode ON

If your script has flags followed by positional arguments:

#!/bin/bash

while getopts "f:" opt; do
  case $opt in
    f) FILE=$OPTARG ;;
  esac
done

shift $((OPTIND -1))  # Remove parsed options from $@

echo "Remaining argument: $1"

 

9. Useful Commands in Scripts

  • grep, awk, sed, cut, xargs, find, curl, wget
find . -name "*.log" -delete

10. Advanced Topics

  • Permissions: chmod, chown
  • Cron jobs (scheduling scripts)
  • Trap and signals
  • Arrays in Bash
  • Here documents (<<EOF)
  • Sourcing other scripts (source or .)
  • Crontab: Scheduling tasks.

  • Debugging: set -x, set -e.

 

other commands:

ls -al ~/.ssh

1. ls

  • This is the list command in Linux/Unix.
  • It shows the contents of a directory (files and folders).

2. -a

  • This option stands for all.
  • By default, ls does not show hidden files (files starting with .).
  • -a ensures you see all files, including hidden ones.
    • Example: .bashrc, .ssh, .profile are hidden files.

3. -l

  • This option stands for long listing format.
  • It shows detailed info about each file, like:
    • File type (d for directory, - for regular file, l for link)
    • Permissions (e.g., rw-r--r--)
    • Number of links
    • Owner
    • Group
    • File size
    • Last modification date
    • File name

4. ~/.ssh

  • ~ is shorthand for your home directory (/home/username).
  • .ssh is a hidden folder in your home directory where SSH keys and configurations are stored.
    • Files you might see:
      • id_rsa ? your private SSH key
      • id_rsa.pub ? your public SSH key
      • authorized_keys ? list of public keys allowed to log in
      • config ? optional SSH client configuration

 


About author

author image

Amrit panta

Fullstack developer, content creator



Scroll to Top