basic

All posts tagged basic by Linux Bash
  • Posted on

    In Bash, managing timers typically involves the use of two primary tools: Bash scripts with built-in timing features (like sleep or date) and Cron jobs (via crontab) for scheduled task execution. Both tools are useful depending on the level of complexity and frequency of the tasks you're managing.

    1. Using Timers in Bash (CLI)

    In Bash scripts, you can manage timers and delays by using the sleep command or date for time-based logic.

    a. Using sleep

    The sleep command pauses the execution of the script for a specified amount of time. It can be used for simple timing operations within scripts.

    Example:

    #!/bin/bash
    
    # Wait for 5 seconds
    echo "Starting..."
    sleep 5
    echo "Done after 5 seconds."
    

    You can also specify time in minutes, hours, or days:

    sleep 10m  # Sleep for 10 minutes
    sleep 2h   # Sleep for 2 hours
    sleep 1d   # Sleep for 1 day
    

    b. Using date for Timing

    You can also use date to track elapsed time or to schedule events based on current time.

    Example (Calculating elapsed time):

    #!/bin/bash
    
    start_time=$(date +%s)  # Get the current timestamp
    echo "Starting task..."
    sleep 3  # Simulate a task
    end_time=$(date +%s)  # Get the new timestamp
    
    elapsed_time=$((end_time - start_time))  # Calculate elapsed time in seconds
    echo "Elapsed time: $elapsed_time seconds."
    

    2. Using crontab for Scheduling Tasks

    cron is a Unix/Linux service used to schedule jobs to run at specific intervals. The crontab file contains a list of jobs that are executed at scheduled times.

    a. Crontab Syntax

    A crontab entry follows this format:

    * * * * * /path/to/command
    │ │ │ │ │
    │ │ │ │ │
    │ │ │ │ └── Day of the week (0-7) (Sunday=0 or 7)
    │ │ │ └── Month (1-12)
    │ │ └── Day of the month (1-31)
    │ └── Hour (0-23)
    └── Minute (0-59)
    
    • * means "every," so a * in a field means that job should run every minute, hour, day, etc., depending on its position.
    • You can use specific values or ranges for each field (e.g., 1-5 for Monday to Friday).

    b. Setting Up Crontab

    To view or edit the crontab, use the following command:

    crontab -e
    

    Example of crontab entries: - Run a script every 5 minutes: bash */5 * * * * /path/to/script.sh - Run a script at 2:30 AM every day: bash 30 2 * * * /path/to/script.sh - Run a script every Sunday at midnight: bash 0 0 * * 0 /path/to/script.sh

    c. Managing Crontab Entries

    • List current crontab jobs: bash crontab -l
    • Remove crontab entries: bash crontab -r

    d. Logging Cron Jobs

    By default, cron jobs do not provide output unless you redirect it. To capture output or errors, you can redirect both stdout and stderr to a file:

    * * * * * /path/to/script.sh >> /path/to/logfile.log 2>&1
    

    This saves both standard output and error messages to logfile.log.

    3. Combining Bash Timers and Cron Jobs

    Sometimes you might need to use both cron and timing mechanisms within a Bash script. For example, if a task needs to be scheduled but also requires some dynamic timing based on elapsed time or conditions, you could use cron to trigger the script, and then use sleep or date inside the script to control the flow.

    Example:

    #!/bin/bash
    
    # This script is triggered every day at midnight by cron
    
    # Wait 10 minutes before executing the task
    sleep 600  # 600 seconds = 10 minutes
    
    # Execute the task after the delay
    echo "Executing task..."
    # Your task here
    

    4. Advanced Scheduling with Cron

    If you need more complex scheduling, you can take advantage of specific cron features: - Use ranges or lists in the time fields: bash 0 0,12 * * * /path/to/script.sh # Run at midnight and noon every day - Run a task every 5 minutes during certain hours: bash */5 9-17 * * * /path/to/script.sh # Every 5 minutes between 9 AM and 5 PM

    5. Practical Examples

    • Backup Every Night:

      0 2 * * * /home/user/backup.sh
      

      This runs the backup.sh script every day at 2 AM.

    • Check Server Health Every Hour:

      0 * * * * /home/user/check_server_health.sh
      

      This runs a script to check the server's health every hour.

    Conclusion

    Managing timers in Bash using cron and sleep allows you to automate tasks, control timing, and create sophisticated scheduling systems. sleep is suitable for in-script delays, while cron is ideal for recurring scheduled jobs. Combining these tools lets you create flexible solutions for a wide range of automation tasks.

  • Posted on

    If you’ve ever used a Linux operating system used on most Virtual Private Servers, you may have heard of bash. It’s a Unix shell that reads and executes various commands.

    What Is Bash?

    Bash, short for Bourne-Again Shell, is a Unix shell and a command language interpreter. It reads shell commands and interacts with the operating system to execute them.

    Why Use Bash Scripts?

    Bash scripts can help with your workflow as they compile many lengthy commands into a single executable script file. For example, if you have multiple commands that you have to run at a specific time interval, you can compile a bash script instead of typing out the commands manually one by one. You then execute the script directly, when it’s necessary.

    Pro Tip Linux has a bash shell command manual. Type man command to find descriptions of all the technical terms and input parameters.

    Get Familiar With Bash Commands

    Bash is available on almost all types of Unix-based operating systems and doesn’t require a separate installation. You will need a Linux command prompt, also known as the Linux terminal. On Windows you would use something like PuTTy. It’s a program that contains the shell and lets you execute bash scripts. 

    1. Comments

    Comments feature a description on certain lines of your script. The terminal doesn’t parse comments during execution, so they won’t affect the output.

    There are two ways to add comments to a script. The first method is by typing # at the beginning of a single-line comment. # Command below prints a Hello World text echo “Hello, world!”

    2. Variables

    Variables are symbols that represent a character, strings of characters, or numbers. You only need to type the variable name in a command line to use the defined strings or numbers.

    To assign a variable, type the variable name and the string value like here: testvar=“This is a test variable”

    In this case, testvar is the variable name and This is a test variable is the string value. When assigning a variable, we recommend using a variable name that’s easy to remember and represents its value.

    To read the variable value in the command line, use the $ symbol before the variable name. Take a look at the example below:

    testvar=“This is a test variable”
    echo $testvar
    

    In order to let the user enter the variable contents use:

    read testvar
    echo $testvar
    

    3. Functions

    A function compiles a set of commands into a group. If you need to execute the command again, simply write the function instead of the whole set of commands.

    There are several ways of writing functions. The first way is by starting with the function name and following it with parentheses and brackets:

    function_name () {
        first command
        second command
    }
    

    Or, if you want to write it in a single line: function_name () { first command; second command; }

    4. Loops

    Loop bash commands are useful if you want to execute commands multiple times. There are three types of them you can run in bash – for, while, and until. The for loop runs the command for a list of items:

    for item in [list]
    do
        commands
    done
    

    The following example uses a for loop to print all the days of the week:

    for days in Monday Tuesday Wednesday Thursday Friday Saturday Sunday
    do
        echo “Day: $days”
    done
    

    On line 2, “days” automatically becomes a variable, with the values being the day names that follow. Then, in the echo command, we use the $ symbol to call the variable values.

    The output of that script will be as follows:

    Day: Monday
    Day: Tuesday
    Day: Wednesday
    Day: Thursday
    Day: Friday
    Day: Saturday
    Day: Sunday
    

    Notice that even with just one command line in the loop script, it prints out seven echo outputs.

    The next type of loop is while. The script will evaluate a condition. If the condition is true, it will keep executing the commands until the output no longer meets the defined condition.

    while [condition]
        do
    commands
    done
    

    5. Conditional Statements

    Many programming languages, including bash, use conditional statements like if, then, and else for decision-making. They execute commands and print out outputs depending on the conditions. The if statement is followed by a conditional expression. After that, it’s followed by then and the command to define the output of the condition. The script will execute the command if the condition expressed in the if statement is true.

    However, if you want to execute a different command if the condition is false, add an else statement to the script and follow it with the command.

    Let’s take a look at simple if, then, and else statements. Before the statement, we will include a variable so the user can input a value:

    echo “Enter a number”
    read num
    if [[$num -gt 10]]
    then
    echo “The number is greater than 10”
    else
    echo “The number is not greater than 10”
    

    OK, so that's it. The 5 building blocks of Bash in plain English. Simple, right?!