Your Webhosting Questions
Answered by the Webhosting Experts
Tags
...
...

Bash Scripts in Linux

Bash, short for Bourne-Again Shell, is a powerful command-line interface (CLI) program that allows users to interact with their systems and execute bash scripts in Linux. Bash provides a way to execute commands, automate tasks, and create custom workflows using bash scripts. Here are the key points about Bash scripting.

  • A Bash script is a file containing a sequence of commands written in the Bash language.
  • These commands are executed by the Bash interpreter line by line.
  • Bash scripts save time by automating repetitive tasks. Instead of typing the same commands repeatedly, you can run a script.
  • You can tailor scripts to your needs, creating personalized solutions.
  • Set up scripts to run at specific times (e.g., daily backups) by scheduling them using cron jobs. 

Creating and Exectuing Your First Bash Script

Let’s create a simple “Hello, World!” script in your server.

  1. Create a file named hello_world.sh using your editor of choice.
  2. Add the shebang line: #!/bin/bash.
    1. #!/bin/bash specifies that the Bash shell should interpret the script.
  3. Write the command: echo “Hivelocity!”.

    Creation of a Bash Script  in Linux Using the nano Text Editor
    Creation of a Bash Script in Linux Using the nano Text Editor
  4. Save the file.
  5. Make it executable using chmod +x /hello_world.sh.
  6. Run it by using either ./hello_world.sh or bash /hello_world.sh. (Bash at the start will run the script using the bash interpreter and should not be used if running a script in a language other than bash). 
Running a Bash Script  in Linux Using the bash Command
Running a Bash Script in Linux Using the bash Command

Bash Script Variables

Variables in Bash scripts are named symbols that represent either strings or numeric values. They allow you to store and reference data within your scripts. To create a variable, provide a name and a value for it. Variable names should be descriptive and cannot start with a number or contain spaces. They can start with an underscore and can have alphanumeric characters. It is also good practice to type variables with uppercase characters.

For example, take this bash script below.

Bash Script Variable Example
Bash Script Variable Example

Executing the script will provide the echo output of the variables that were set in the beginning of the script.

Bash Script Execution Displaying Output of Variables
Bash Script Execution Displaying Output of Variables

Other Shebang (#!) Examples

Shebang (#!) specifics the interpreter used for the script you’ve created and can be used for other languages other than bash.

  • #!/bin/bash: Specifies the Bash interpreter.
  • #!/usr/bin/env python: Uses the Python interpreter found in the user’s $PATH.
  • #!/usr/bin/perl: Executes the script using the Perl binary.

Common Operations for Bash Scripts in Linux

  1. Sleep command using “sleep 3” to pause an execution for a specified time in seconds. 
  2. Reading input from a user.
    read -p “Enter your name:” USERNAME
    echo “Hello, $USERNAME!”
  3. Loops to execute commands repeatedly 
    for i in {1..5}; do
    echo “Iteration $i”
    done

  4. Conditional Statements to make decisions based on conditions

    age=25
    if [ “$age” -ge 18 ]; then
    echo “You are an adult.”
    else
    echo “You are a minor.”
    fi

  5. Functions to define reusable code blocks
    greet() {
    echo “Hello from a function!”
    }
    greet

  6. File operations to create directories, read files, and delete files
    mkdir my_directory
    cat myfile.txt
    rm unwanted_file.txt

  7. Math operations to perform calculation
    result=$((5 + 3))
    echo “5 + 3 = $result”

  8. Checking file existence to verify if a file does exist

    if [ -f myfile.txt ]; then
    echo “File exists.”
    else
    echo “File does not exist.”
    fi

Scheduling your Script via a Cron Job

Adding a script to a cron job allows you to schedule it to run automatically at specified intervals.

  1. For demonstration purposes, let’s assume our script prints the system date and time and appends it to a log file.
    #!/bin/bash
    echo “$(date +’%Y-%m-%d %T’) – Hello, cron!” >> /home/user/log.txt

    Make sure the script is executable with chmod +x my_script.sh.

  2. Add the script to the user’s crontab by opening the crontab editor using crontab -e
  3. Append the following line to schedule the script to run every day at 3:00 AM using 

    0 3 * * * /path/to/my_script.sh

  4. Save and close the editor followed by ensuring that the script can be executed properly with chmod +x /path/to/my_script.sh.

For a useful tool on how to handle the time format of a cron job, check out the useful tool here – https://crontab-generator.org/

Need More Personalized Help?

If you have any further issues, questions, or would like some assistance checking on this or anything else, please reach out to us from your my.hivelocity.net account and provide your server credentials within the encrypted field for the best possible security and support.

If you are unable to reach your my.hivelocity.net account or if you are on the go, please reach out from your valid my.hivelocity.net account email to us here at: [email protected]. We are also available to you through our phone and live chat system 24/7/365.

Tags +
...