Bash Shell – TecAdmin https://tecadmin.net How to guide for System Administrator's and Developers Tue, 27 Dec 2022 17:17:44 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.1 Checking If a Command Succeeded in Bash Using the `$?` Special Variable https://tecadmin.net/check-if-a-command-succeeded-in-bash/ https://tecadmin.net/check-if-a-command-succeeded-in-bash/#respond Tue, 27 Dec 2022 17:17:44 +0000 https://tecadmin.net/?p=33222 In Bash, it is often necessary to check if a command succeeded or failed. For example, you may want to execute different commands based on the success or failure of a command, or you may want to perform error handling in a script. To check if a command succeeded or failed in Bash, you can [...]

The post Checking If a Command Succeeded in Bash Using the `$?` Special Variable appeared first on TecAdmin.

]]>
In Bash, it is often necessary to check if a command succeeded or failed. For example, you may want to execute different commands based on the success or failure of a command, or you may want to perform error handling in a script. To check if a command succeeded or failed in Bash, you can examine the exit status of the command. The exit status of a command is a numerical value that indicates the success or failure of the command. A command with an exit status of 0 indicates success, and a command with a non-zero exit status indicates failure.

In this article, we will explore different ways to check the exit status of a command in Bash, including using the `$?` special variable, using the `&&` and `||` operators, and using scripts and functions. Understanding how to check the exit status of a command in Bash can be helpful in various scenarios when working with Bash.

Checking If a Command Succeeded in Bash

In Bash, you can check if a command succeeded or failed by examining the exit status of the command. The exit status of a command is a numerical value that indicates the success or failure of the command. A command with an exit status of 0 indicates success, and a command with a non-zero exit status indicates failure.

To check the exit status of a command in Bash, you can use the $? special variable, which stores the exit status of the most recently executed command.

For example, consider the following command:

ls -l /etc/ 

This command lists the contents of the `/etc` directory in long format. To check if this command succeeded, you can use the following code:

ls -l /etc/
if [ $? -eq 0 ]; then
    echo "Command succeeded"
else
    echo "Command failed"
fi

This code checks the exit status of the ls command by examining the value of the $? special variable. If the value of `$?` is `0`, the command succeeded, and the code prints “Command succeeded”. If the value of `$?` is non-zero, the command failed, and the code prints “Command failed”.

Check Exit Status of a Function

You can also use the `$?` special variable to check the exit status of a command in a script or function. For example, consider the following script:

#/usr/bin/env bash

check_command() {
    command
    if [ $? -eq 0 ]; then
        return 0
    else
        return 1
    fi
}

check_command ls -l /etc/
if [ $? -eq 0 ]; then
    echo "Command succeeded"
else
    echo "Command failed"
fi

This script defines a function check_command that takes a command as an argument and checks the exit status of the command. The function returns `0` if the command succeeded and `1` if the command failed. The script then calls the check_command function with the ls command and checks the exit status of the function by examining the value of the `$?` special variable. If the value of `$?` is `0`, the command succeeded, and the script prints “Command succeeded”. If the value of `$?` is `1`, the command failed, and the script prints “Command failed”.

Check Exit Status Using `&&` And `||` in Bash

In addition to using the `$?` special variable, you can also use the `&&` and `||` operators to check the exit status of a command and execute different commands based on the result. For example, consider the following code:

ls -l /etc/ && echo "Command succeeded" || echo "Command failed"

This code checks the exit status of the `ls`‘ command and executes different commands based on the result. If the ls command succeeded, the code prints “Command succeeded”. If the ls command failed, the code prints “Command failed”.

Conclusion

In conclusion, checking if a command succeeded or failed in Bash is a useful task that can be accomplished by examining the exit status of the command. The exit status of a command is a numerical value that indicates the success or failure of the command. A command with an exit status of `0` indicates success, and a command with a non-zero exit status indicates failure. To check the exit status of a command in Bash, you can use the $? special variable, which stores the exit status of the most recently executed command.

You can also use the $? special variable to check the exit status of a command in a script or function or use the `&&` and `||` operators to check the exit status and execute different commands based on the result. Understanding how to check the exit status of a command in Bash can be helpful in various scenarios, such as when you want to execute different commands based on the success or failure of a command or when you want to perform error handling in a script.

The post Checking If a Command Succeeded in Bash Using the `$?` Special Variable appeared first on TecAdmin.

]]>
https://tecadmin.net/check-if-a-command-succeeded-in-bash/feed/ 0
How to Generate Random String in Bash https://tecadmin.net/how-to-generate-random-string-in-bash/ https://tecadmin.net/how-to-generate-random-string-in-bash/#respond Mon, 19 Dec 2022 13:16:13 +0000 https://tecadmin.net/?p=18442 A random string is a sequence of characters that is generated randomly, rather than being determined by a set pattern or predetermined sequence. Random strings are often used as passwords, keys, or identifiers, and they can be generated using a variety of methods. Random strings can be generated using a computer program or a physical [...]

The post How to Generate Random String in Bash appeared first on TecAdmin.

]]>
A random string is a sequence of characters that is generated randomly, rather than being determined by a set pattern or predetermined sequence. Random strings are often used as passwords, keys, or identifiers, and they can be generated using a variety of methods.

Random strings can be generated using a computer program or a physical random number generator. The length and character set of a random string can be specified in the generation process. For example, a random string might be generated using only uppercase letters and digits, or it might include a combination of letters, digits, and special characters.

Generate Random String in Linux

To generate a random string in Bash, you can use the `openssl` command and the `base64` encoding function. Here is an example of how you can generate a random string of length 10:

openssl rand -base64 10 

This will generate a random string of length 10 using base64 encoding. The output will be a string of characters that includes letters, numbers, and special characters.

You can also use the `tr` command to remove any characters that you don’t want to include in your random string. For example, to generate a random string of length 10 that only includes uppercase letters and digits, you can use the following command:

openssl rand -base64 10 | tr -dc 'a-zA-Z0-9' 

This will generate a random string of length 10 that only includes uppercase letters and digits.

You can adjust the length of the random string by changing the number passed to the `-base64` option. For example, to generate a random string of length 20, you can use the following command:

openssl rand -base64 20 | tr -dc 'a-zA-Z0-9' 

This will generate a random string of length 20 that only includes uppercase letters and digits.

Conclusion

Random strings are useful because they are difficult to guess or predict, which makes them suitable for use as passwords or other forms of authentication. They can also be used to randomly assign identifiers to objects or records in a database, which can help to ensure that the identifiers are unique and not predictable.

This tutorial helped you to generate random strings in bash shell scripts and Linux command line interface.

The post How to Generate Random String in Bash appeared first on TecAdmin.

]]>
https://tecadmin.net/how-to-generate-random-string-in-bash/feed/ 0
Efficiently Reading a File Line by Line in a Shell Script https://tecadmin.net/reading-file-line-by-line-in-linux-shell-script/ https://tecadmin.net/reading-file-line-by-line-in-linux-shell-script/#respond Fri, 16 Dec 2022 10:52:21 +0000 https://tecadmin.net/?p=6390 Reading a file line by line is a common task in many shell scripts, as it allows you to process each line of a file separately and perform actions based on the contents of each line. There are several ways to read a file line by line in a Linux shell script, but some methods [...]

The post Efficiently Reading a File Line by Line in a Shell Script appeared first on TecAdmin.

]]>
Reading a file line by line is a common task in many shell scripts, as it allows you to process each line of a file separately and perform actions based on the contents of each line. There are several ways to read a file line by line in a Linux shell script, but some methods are more efficient than others. In this article, we’ll explore some of the most efficient ways to read a file line by line in a Linux shell script.

Using while loop

The most basic way to read a file line by line in a shell script is to use a while loop and the read command. The read command reads a line of input from the file and stores it in a variable, which can then be processed by the script. The while loop allows you to iterate through the lines of the file until the end is reached. Here’s an example of how this might look:

#!/usr/bin/env bash

# Read file line by line
while read line; do
  # Process single line content 
  echo "$line"
done < file.txt

This method is simple and easy to understand, but it has some limitations. One limitation is that the read command can only read one line at a time, so it can be slower for large files with many lines. In addition, the read command can only read from standard input (stdin), so you must use the < operator to redirect the contents of the file to stdin. This can be inconvenient if you need to read from multiple files or if you want to read from a file that is not in the current directory.

Using while loop with cat

A more efficient way to read a file line by line in a shell script is to use the cat command in combination with a while loop. The cat command reads a file and outputs its contents to stdout, which can then be processed by the while loop. Here’s an example of how this might look:

#!/usr/bin/env bash

# Read file line by line
while read line; do
  # Process single line content 
  echo "$line"
done < <(cat file.txt)

This method is more efficient than the read command because it reads the entire file into memory at once, rather than reading one line at a time. This can be faster for large files with many lines. In addition, the cat command can read from any file, not just stdin, so you can use it to read from multiple files or files that are not in the current directory.

Using while loop with sed

Another efficient way to read a file line by line in a shell script is to use the sed command in combination with a while loop. The sed command is a powerful text processing tool that can read a file and output its contents to stdout, one line at a time. Here’s an example of how this might look:

#!/usr/bin/env bash

# Read file line by line
while read line; do
  # Process single line content 
  echo "$line"
done < <(sed -n -e 1p file.txt)

This method is similar to the cat command, but it is more efficient because it only outputs one line at a time. This can be faster for large files with many lines. In addition, the sed command has many options and features that can be used to manipulate the output, so it is a very flexible tool for text processing.

In summary, there are several ways to read a file line by line in a Linux shell script.

The post Efficiently Reading a File Line by Line in a Shell Script appeared first on TecAdmin.

]]>
https://tecadmin.net/reading-file-line-by-line-in-linux-shell-script/feed/ 0
Check if a Variable Contains a Number in Bash https://tecadmin.net/bash-check-if-a-variable-contains-a-number/ https://tecadmin.net/bash-check-if-a-variable-contains-a-number/#respond Fri, 21 Oct 2022 02:10:41 +0000 https://tecadmin.net/?p=32148 A number is a combination of 0-9 digits—the Bash variables stores all value in the form of strings. Even if the stored value is in string format, we can perform all the arithmetical operations if the stored value is a valid number. As a best practice, we should verify the values of variables before performing [...]

The post Check if a Variable Contains a Number in Bash appeared first on TecAdmin.

]]>
A number is a combination of 0-9 digits—the Bash variables stores all value in the form of strings. Even if the stored value is in string format, we can perform all the arithmetical operations if the stored value is a valid number. As a best practice, we should verify the values of variables before performing the arithmetic operations.

A number can be an integer number, a floating point number, or a positive/negative number that prefixes with a “+ and -” symbol. In this tutorial, we have discussed a few methods to verify that the variable contains only digits, integers, and double or float values, not alphabets.

Using Equal Tilde (=~) Operator

The regular expression is a quick and easy way for checking if a value is a number. In Bash scripting, the equal tilde (=~) operator is used to compare a value with a regular expression. That can be used with the bash if statement:

#!/usr/bin/env bash
# Shell script to check if the input number is an integer

read -p "Please enter a number: " VAR

if [[ $VAR =~ ^[0-9]+$ ]]; then
   echo "${VAR} is a number"
else
   echo "${VAR} is not a number"
fi

Write the above snippet in a shell script and execute. first-time input a value number.

First run
Please enter a number: 12 12 is a number

Again run the script with some alphabets and check the output:

Second run
Please enter a number: 1a2b 12a is not a number

Check if Floating Point Number

A floating Point Number is an integer type that represents a number that can hold a fractional part (also known as a float). As the name suggests, these numbers can take on different values at different places and times. Floating point numbers are typically used to represent numbers with a decimal point in them. For example, 1.0, 0.6, and 10.26 are all floating-point numbers.

Write a new shell script that considers a floating point number as a valid number.

#!/usr/bin/env bash
# Shell script to check if the input number is a number
# That can be a integer or floating point number

read -p "Please enter a number: " VAR

if [[ $VAR =~ ^[0-9]+([.][0-9]+)?$ ]]; then
   echo "${VAR} is a number"
else
   echo "${VAR} is not a number"
fi

Execute the above script by inputting some floating point numbers. This script will consider all floating point numbers as valid numbers.

First run
Please enter a number: 12.10 12.10 is a number

Using Switch Case Statment

Some of the scripts required to have a case statement. That is similar to switch statements in other programming languages. We can also use regular expressions in case statement options and verify if the given input is a number.

#!/usr/bin/env bash
# Shell script to check if the input number is a number
# using switch case statement

read -p "Please enter a number: " VAR

case $VARin
    ''|*[!0-9]*) echo "${VAR} is not a number" ;;
    *) echo "${VAR} is a number" ;;
esac

Execute the above script multiple times with different inputs and see the results:

First run
Please enter a number: 12 12 is a number

Check if Number Contains +/- Signs

In the above methods, we have checked for integer values that contain 0-9 digits only, A floating point number that also contains a fraction of values known as decimal numbers. In some cases, a number also can be positive or negative. Any number with no prefix or with + is a positive number. The number with - prefix is negative number.

Update the regular expression, to consider a number that has a +/- sings before it.

#!/usr/bin/env bash
# Shell script to check if the input number is a number
# and can be a positive or negative number

read -p "Please enter a number: " VAR

if [[ $VAR =~ ^[+-]?[0-9]+$ ]]; then
   echo "${VAR} is a number"
else
   echo "${VAR} is not a number"
fi

Run the above script with different-2 inputs and check the results.

First run
Please enter a number: 12 12 is a number
Second run
Please enter a number: -12 -12 is a number
Third run
Please enter a number: +12 +12 is a number

Check If a Number is Postive or Negative

While performing arithmetic operations in bash scripting, you should verify the input values. The below shell script will help you to check if the input number is a positive number or a negative number.

#!/usr/bin/env bash
# Shell script to check if the input number
# is a positive number or negative number

read -p "Please enter a number: " VAR

## Check if the input is a valid number
if [[ $VAR =~ ^[+,-]?[0-9]+$ ]]; then
   ## Check if the input is a positive or negative number
   if [[ $VAR =~ ^[-][0-9]+$ ]]; then
      echo "${VAR} is a negative number"
   else
      echo "${VAR} is a positive number"
   fi
else
   echo "${VAR} is not a number"
fi

Run the above script with positive and negative numbers. Then check the results.

First run
Please enter a number: 12 12 is a positive number
Second run
Please enter a number: -12 -12 is a negative number
Third run
Please enter a number: +12 +12 is a positive number

Conclusion

A number is a collection of digits from 0 to 9. Any number can be a positive or negative number. A number can be an integer or floating point number. This tutorial helped you check whether the given value is a number or not in bash scripting.

The post Check if a Variable Contains a Number in Bash appeared first on TecAdmin.

]]>
https://tecadmin.net/bash-check-if-a-variable-contains-a-number/feed/ 0
Comparing Strings in Bash: Techniques and Best Practices https://tecadmin.net/compare-strings-in-bash/ https://tecadmin.net/compare-strings-in-bash/#respond Sun, 09 Oct 2022 16:29:36 +0000 https://tecadmin.net/?p=6644 Comparing strings is a common task when working with shell scripts, user input, or string data. In the shell, you may need to check if a value exists in another string, find if two strings have the same length, test for the beginning or end of a word, or any other type of comparison. The [...]

The post Comparing Strings in Bash: Techniques and Best Practices appeared first on TecAdmin.

]]>
Comparing strings is a common task when working with shell scripts, user input, or string data. In the shell, you may need to check if a value exists in another string, find if two strings have the same length, test for the beginning or end of a word, or any other type of comparison. The standard Unix tools don’t provide many options for comparing strings; the traditional lexical comparison (like checking if two words are the same length and comparing each character individually) is hard to implement efficiently in code and isn’t as valuable for a dynamic language like Bash.

This article explains different ways to compare strings in Bash and several related commands.

String Comparison Operators

We can use comparison operators with bash if statements to compare two strings. Here is the list of comparison operators to work with strings in the bash shell.

Operator Details
string1 == string2 Returns true if both strings are equal.
string1 != string Returns true if both strings are not equal.
string =~ regex Compare string1 with regular expression and return true matches
-z string Return true if the given string length is zero (0)
-n string Return true if the given string length is not zero

Now, we will discuss the above comparison operator one by one with examples.

Compare Two Strings in Bash (==)

If you need to check if two strings are equal, use the == operator. These operators compare the left operand with the right operand and return true if both match.

Let’s understand with an example. In a shell script initialize two variables with a string. Then use the if statement to compare whether both strings are equal or not using the == operator.

#!/usr/bin/env bash

STR1="TecAdmin"
STR2="TecAdmin"

if [ "$STR1" == "$STR2" ]
then
    echo "Both strings are equal"
else
    echo "Both strings are not equal"
fi

Run the above shell script in a bash shell and check for the results.

Output:
Both strings are equal

Now, change both variables’ values with different strings. Then again the script and see the results.

Check Two Strings are Not Equal (!=)

Sometimes we are required to check if both strings are not equal. You can use != operator to test if two strings are not equal. Let’s check with an example:

#!/usr/bin/env bash

STR1="TecAdmin"
STR2="HelloWorld"

##Check if both strings are not equal
if [ "$STR1" != "$STR2" ]
then
    echo "True, both strings are not equal"
else
    echo "False, both strings are equal"
fi

Run the above shell script in a bash shell and check for the results.

Output:
True, both strings are not equal

Compare Strings with Regular Expression

We can also compare string with a regular expression in bash scripts. While using the string comparison with regular expression with an if statement, you should always enclose with [[ ]] quotes. The below example will show help you to check if the variable contains the string that begins with a specific string.

#!/usr/bin/env bash

STR="TecAdmin"

if [[ "$STR" =~ ^Tec ]]
then
    echo "Yes, the regular expression matches "
else
    echo "Regular expression not matches "
fi

Output:
Yes, the regular expression matches

Let’s check with another example. In this script, we will prompt the user to input a number. Then verify whether the input value is a number or not. A number container the digits between 0 to 9.

#!/usr/bin/env bash

read -p "Input a number: " VAR

## Check if the input value is a number
if [[ "$VAR" =~ ^[0-9]+$ ]]
then
    echo "Given input is a number"
else
    echo "Sorry, input is not a number"
fi

Run the above bash script and provide the input when prompted.

First run:
Input a number: 12
Given input is a number

Again run this script but this time input a non-numeric value and see the results.

Second run:
Input a number: 1234a
Sorry, input is not a number

Check if a String is Empty

While taking user input in a shell script, it’s important to check that the input string is not empty. You can use -z returns true if the string is empty.

#!/usr/bin/env bash

read -p "Type anything: " VAR

if [[ -z $VAR ]]; then
  echo "Empty string"
else
  echo "You type: ${VAR}"
fi

Execute the above shell script in a bash shell and just hit enter when prompted for user input.

First run:
Type anything:
Empty string

Again run the above script and type something when prompted.

Second run:
Type anything: TecAdmin
You type: TecAdmin

Conclusion

In this tutorial, we have discussed string comparisons in the bash script. You can also check if a string is empty or not. Also provides an example to check if the input value is a number or not.

The post Comparing Strings in Bash: Techniques and Best Practices appeared first on TecAdmin.

]]>
https://tecadmin.net/compare-strings-in-bash/feed/ 0
How to run a command on bash script exits https://tecadmin.net/how-to-run-a-command-on-bash-script-exits/ https://tecadmin.net/how-to-run-a-command-on-bash-script-exits/#respond Tue, 02 Aug 2022 03:03:48 +0000 https://tecadmin.net/?p=30843 Shell scripts are handy for automating tasks like backup databases, clearing log files, etc. You need to perform some tasks when the script finishes the execution. No matter at which stage the script is finished. For example, a script that clears the log files from the system. The script first checks the size of the [...]

The post How to run a command on bash script exits appeared first on TecAdmin.

]]>
Shell scripts are handy for automating tasks like backup databases, clearing log files, etc. You need to perform some tasks when the script finishes the execution. No matter at which stage the script is finished.

For example, a script that clears the log files from the system. The script first checks the size of the log file, if the log file size is lower than the specified size, the script exits. In that case, you still want to run a block of code.

To do this, we can use the trap command to catch the EXIT signal and execute a command or function. Below is the sample shell script to run a function or command on shell script exit.

#!/usr/bin/env bash

on_exit(){
  echo "Your script ended now"
}

trap 'on_exit' EXIT

echo "Hello world"

Run the above script and see the results

Output
Hello world Your script ended now

Hope, this quick how-to guide helps you to improve your shell script writing skills.

The post How to run a command on bash script exits appeared first on TecAdmin.

]]>
https://tecadmin.net/how-to-run-a-command-on-bash-script-exits/feed/ 0
How to Detect and Handle Errors in Your Bash Scripts https://tecadmin.net/execute-specific-command-on-error-in-bash-script/ https://tecadmin.net/execute-specific-command-on-error-in-bash-script/#respond Sat, 30 Jul 2022 21:53:56 +0000 https://tecadmin.net/?p=30831 We can use the trap command to catch the error signal system by the system during script execution. Then you can execute a shell command or call a function. In this way, you can execute your custom script code on an error that occurred in a bash script. This can be helpful to revert any [...]

The post How to Detect and Handle Errors in Your Bash Scripts appeared first on TecAdmin.

]]>
We can use the trap command to catch the error signal system by the system during script execution. Then you can execute a shell command or call a function. In this way, you can execute your custom script code on an error that occurred in a bash script.

This can be helpful to revert any partial changes, close database connections, or email status to the concerned persons, etc. You can use trap commands with `ERR` signals like:

trap 'on_error_function' ERR

When an error is generated in a shell script, it will execute a function named ‘on_error_function’ of your shell script. Instead of calling a function, you can simply run a command as well.

Example: Execute a function on Error in Bash

Let’s understand with an example. Create a sample shell script, and create a function with any name. Then add the trap command with the function for ERR signal. Next, add a simple command that generates an error.

#!/usr/bin/env bash

on_error(){
  echo "Some error occurred"
}

trap 'on_error' ERR

ls ~/dir_not_exists

Execute the above script and you should see the results below:

Output:
ls: cannot access '/home/tecadmin/dir_not_exists': No such file or directory Some error occurred

You can see that the error is trapped and the function on_error() is executed by the bash script.

Example: Execute a command on Error in Bash

Let’s see one more example. Here we will execute a command when any error will occur in the shell script.

#!/usr/bin/env bash

trap 'echo Ohhh no!' ERR

ls ~/dir_not_exists

In the above script, we do not define any separate function. Simply run an echo command on error. Execute the above script and see the results.

Output:
ls: cannot access '/home/tecadmin/dir_not_exists': No such file or directory Ohhh no!

Example: Get the line number of error occurred

You can also find out the line number, where the error occurred in the bash script along with the script name. To do this use the bash inbuilt ‘caller’.

#!/usr/bin/env bash

on_error(){
        echo "Error found in: $(caller)" >&2
}

trap 'on_error' ERR

ls ~/dir_not_exists

Execute the above script and see the results. You will see the script name and the line number, where the error occurred.

Output:
ls: cannot access '/home/tecadmin/dir_not_exists': No such file or directory Error found in: 9 ./script.sh

Conclusion

Thanks for reading this article. Hopefully, this tutorial helps you with better writing of shell scripts by catching the error and taking some action.

Also, remember that the ERR trap catches the runtime errors only. Like if any command returns the non-zero status code. It doesn’t catch the syntax errors, because in the case of syntax error the script fails without running any command.

The post How to Detect and Handle Errors in Your Bash Scripts appeared first on TecAdmin.

]]>
https://tecadmin.net/execute-specific-command-on-error-in-bash-script/feed/ 0
How to Backup Website to Amazon S3 using Shell Script https://tecadmin.net/backup-website-to-amazon-s3-using-shell-script/ https://tecadmin.net/backup-website-to-amazon-s3-using-shell-script/#respond Wed, 23 Mar 2022 12:44:05 +0000 https://tecadmin.net/?p=28756 Amazon Simple Storage Service (Amazon S3) is an cloud based object storage device. It is a low cost storage widely used for the backup or static website content. You can use AWSCLI command line utility for managing s3 bucket and its content. In this tutorial, you will learn about backup a website to Amazon s3 [...]

The post How to Backup Website to Amazon S3 using Shell Script appeared first on TecAdmin.

]]>
Amazon Simple Storage Service (Amazon S3) is an cloud based object storage device. It is a low cost storage widely used for the backup or static website content.

You can use AWSCLI command line utility for managing s3 bucket and its content. In this tutorial, you will learn about backup a website to Amazon s3 bucket using a shell script.

Installing AWS CLI

The AWS CLI packages are available under the default repositories on most of the Linux systems. You can install it by running one of the following commands:

sudo dnf install awscli    ## Fedora, Redhat and CentOS
sudo apt install awscli    ## Ubuntu, Debian and Linux Mint

You can also another article to install latest AWS CLI on any Linux system.

Once the installation finished, check the awscli version by executing:

aws --version  

Create A Shell Script

Now, create a shell script file on your system and add the below content. For this tutorial, I created file using:

nano /scripts/s3WebsiteBackup.sh   

and added the following content:

#/usr/bin/env bash

################################################################
##
## Shell script to archive website code and upload to S3 bucket.
## Written by: Rahul Kumar
## Website: https://tecadmin.net
##
#################################################################


S3_BUCKET_NAME=""
DIR_TO_BACKUP="/var/www/html"
BACKUP_FILENAME='website'

TODAY=`date +%Y%m%d`
YY=`date +%Y`
MM=`date +%m`
AWSCMD="/usr/local/bin/aws"
TARCMD="/usr/bin/tar"

${TARCMD} czf /tmp/${BACKUP_FILENAME}-${TODAY}.tar.gz

${AWSCMD} cp /tmp/${BACKUP_FILENAME}-${TODAY}.tar.gz s3://${S3_BUCKET_NAME}/${YY}/${MM}/


if [ $? -eq 0 ]; then
	echo "Backup successfully uploaded to s3 bucket"
else
    echo "Error in s3 backup"
fi

Make sure to update S3_BUCKET_NAME and DIR_TO_BACKUP in the script. You can also change the backup file name in BACKUP_FILENAME variable.

Save file and close it. Now, you have a shell script to backup website content to s3 buckets.

Running Shell Script

Make the shell script executable by running the following command.

chmod +x /scripts/s3WebsiteBackup.sh 

Now, you can test the script by executing it manually.

bash /scripts/s3WebsiteBackup.sh 

On successful, backups will be uploaded to s3 bucket. Which you can view using aws s3 ls command.

Schedule Script in Cron

Next, schedule your script to crontab to automate this job. To edit the crontab of current user, type:

crontab -e 

Add the following entry to the crontab:

0 2 * * * bash /scripts/s3WebsiteBackup.sh 

Save file and close the editor.

Wrap Up

This tutorial provides you a shell script to backup website content to the S3 bucket. Also includes the instruction to run this script.

The post How to Backup Website to Amazon S3 using Shell Script appeared first on TecAdmin.

]]>
https://tecadmin.net/backup-website-to-amazon-s3-using-shell-script/feed/ 0
Creating Menu in Shell Script (Linux Select Command) https://tecadmin.net/bash-select/ https://tecadmin.net/bash-select/#comments Fri, 10 Dec 2021 09:33:16 +0000 https://tecadmin.net/?p=28352 Bash Select construct is used to create a numbered menu from the list of items. That is helpful for shell scripts that required user selection across multiple items. Syntax The select statement has a similar syntax as ‘for loop’ and it is: select ITEM in [List] do [commands] done Here the List can be an [...]

The post Creating Menu in Shell Script (Linux Select Command) appeared first on TecAdmin.

]]>
Bash Select construct is used to create a numbered menu from the list of items. That is helpful for shell scripts that required user selection across multiple items.

Syntax

The select statement has a similar syntax as ‘for loop’ and it is:

select ITEM in [List]
do
     [commands]
done

Here the List can be an array, a range of numbers, a series of strings separated by space, the output of a command, etc. And when the select construct will be invoked, each item from the list will be printed with a numbered sequence. The construct will continue to run until the break command is executed.

Bash Select Example

Let’s understand the select construct with an example. Here we have created a bash script named brand.sh and the select command is used to retrieve the data from the list as a menu. The script will first print the name of all the brands in the list and then it will ask the user to choose any one of them and it will print the name of the selected brand.

#!/bin/bash

select brand in Apple Google Microsoft Amazon Meta
do
  echo "You have chosen $brand"
done

Run the script with ‘bash brand.sh’. You will see the following output.

Output
1) Apple 2) Google 3) Microsoft 4) Amazon 5) Meta #? 1 You have chosen Apple #? 3 You have chosen Microsoft #? ^C

Press CTRL+C to exit.

One More Example

Let’s take another example of the select construct to see how it works with a case statement.

Here we will create a new file named select.sh and once we will run the file, the user will select any item, and then the case statement will match the item with the case value. If no value is matched then ‘Invalid entry’ will print.

#!/bin/bash 

echo "Which Operating System do you like?"

select os in Ubuntu LinuxMint Windows8 Windows7 WindowsXP
do
case $os in 
  "Ubuntu"|"LinuxMint")
     echo "I also use $os."
     ;;
  "Windows8" | "Windows10" | "WindowsXP")
     echo "Why don't you try Linux?"
   ;;
*)
echo "Invalid entry."
break
;;
esac
done

Now run the script with bash select.sh and you will see the following output.

Output
1) Ubuntu 3) Fedora 5) Windows7 2) LinuxMint 4) Windows8 6) WindowsXP #? 1 I also use Ubuntu. #? 2 I also use LinuxMint. #? 4 Why don't you try Linux? #? 7 Invalid entry.

Conclusion

This guide explains to use of the select command in bash scripting.

The post Creating Menu in Shell Script (Linux Select Command) appeared first on TecAdmin.

]]>
https://tecadmin.net/bash-select/feed/ 4
Bash Break and Continue https://tecadmin.net/bash-break-and-continue/ https://tecadmin.net/bash-break-and-continue/#respond Mon, 08 Nov 2021 14:00:54 +0000 https://tecadmin.net/?p=28318 Loops in a programming language, allows you to run commands multiple times till a particular condition. Even in Bash we have mainly three loops – until, while, and for. Sometimes you need to alter the flow of a loop and terminate it. Here comes the Break and Continue statement. They help you in terminating or [...]

The post Bash Break and Continue appeared first on TecAdmin.

]]>
Loops in a programming language, allows you to run commands multiple times till a particular condition. Even in Bash we have mainly three loops – until, while, and for. Sometimes you need to alter the flow of a loop and terminate it. Here comes the Break and Continue statement. They help you in terminating or managing the cycle of a loop. Here we will show you how you can use Break and Continue statements in Bash.

Bash Break Statement

The Bash Break statement helps in terminating the current loop and passing program control to the command that follows the terminated loop. We use it to exit from a while, until, for or select loops.

The syntax of the Break statement is: break[n]. Where [n] is an optional argument that must be greater than or equal to 1.

Let’s understand the Break statement with an example. Here is a simple program with a for loop that will iterate over a range of values from 1-20 with an increment of 2. The conditional statement in the third line will check the expression and when val=9 is true, the break statement will run and the loop will be terminated.

for val in {1..20..2}
do
  If [[ $val -eq 9 ]]
  then
     break
  else
  echo "printing {val}"
fi
done

Further, if you want to exit from a second loop or outer loop then you can use ‘break 2’. This will tell that loop too needs to be terminated.

Bash Continue

We use the Break statement to exit the entire loop when a condition is satisfied. What if you want to skip a particular block of code instead of exiting the entire loop? In such conditions, we use the Bash Continue statement. The Continue statement lets you skip the execution of a code block when the condition is satisfied or we can say that statement skips the remaining part of the code for the current iteration and passes control to the next iteration of the loop.

The syntax of the Continue statement is: continue [n]. Again [n] is an optional argument that can be greater than or equal to 1.

Let’s understand the Continue statement with an example. Here we have a simple program and in that when the current iterated item will be equal to 2, the continue statement will return to the beginning of the loop and continue with the next iteration.

i=0

while [[ $i -lt 5 ]]; do
  ((i++))
  if [[ "$i" == '2' ]]; then
    continue
  fi
  echo "No: $i"
done

echo 'Done!'

The output of this program will be as follows:

Output
No: 1 No: 3 No: 4 No: 5 Done! Let’s take another example to clear the concept of the Continue statement. The following program prints the number between 1 to 31 that is divisible by 5. If the number is not divided by 5 then the Continue statement skips the ‘echo’ command and passes the control to the next iteration of the loop.
for i in {1..31}; do
if [[ $(($i%5)) -ne 0]]; then
continue
fi
echo “Divisible by 5: $i”
done
The program will have the following output.
Output
Divisible by 5: 5 Divisible by 5: 10 Divisible by 5: 15 Divisible by 5: 20 Divisible by 5: 25 Divisible by 5: 30

The post Bash Break and Continue appeared first on TecAdmin.

]]> https://tecadmin.net/bash-break-and-continue/feed/ 0