bash – TecAdmin https://tecadmin.net How to guide for System Administrator's and Developers Mon, 09 Jan 2023 02:23:29 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.1 10 Most Popular Open Source Linux Shells https://tecadmin.net/most-popular-open-source-linux-shells/ https://tecadmin.net/most-popular-open-source-linux-shells/#respond Mon, 09 Jan 2023 02:23:29 +0000 https://tecadmin.net/?p=33682 The Linux shell is a command-line interface that allows users to interact with the operating system and execute commands. There are several different types of Linux shells available, each with its own set of features and characteristics. In this article, we will introduce the 10 most popular open-source Linux shells, which are widely used by [...]

The post 10 Most Popular Open Source Linux Shells appeared first on TecAdmin.

]]>
The Linux shell is a command-line interface that allows users to interact with the operating system and execute commands. There are several different types of Linux shells available, each with its own set of features and characteristics. In this article, we will introduce the 10 most popular open-source Linux shells, which are widely used by developers, system administrators, and other users around the world.

1. Bash Shell

Bash, or the Bourne Again Shell, is the default shell on most Linux and Unix-like operating systems. It is a widely-used, powerful, and flexible shell that is suitable for a wide range of tasks.

The main features and characteristics of the bash shell are:

  • Command history: Bash allows users to easily access and execute previous commands using the up and down arrow keys.
  • Job control: Bash supports job control, which allows users to run processes in the background, interrupt them, and resume them.
  • Shell scripts: Bash supports shell scripting, which allows users to automate tasks by writing scripts that execute a series of commands.
  • Aliases: Bash allows users to create aliases for frequently used commands, which can save time and improve efficiency.

2. Zsh Shell

Zsh, or the Z shell, is a feature-rich and highly customizable shell that is popular among power users. It has a large number of built-in features and supports a wide range of plugins and themes.

  • Command completion: Zsh supports programmable command completion, which allows users to customize the way command completions are displayed and triggered.
  • Plugins: Zsh supports a wide range of plugins that can add additional features and functionality to the shell.
  • Themes: Zsh supports customizable themes that allow users to change the appearance of the shell prompt and other elements.
  • Advanced command history: Zsh includes advanced command history features, such as the ability to search and execute previous commands.

3. Fish Shell

Fish, or the Friendly Interactive Shell, is a modern and user-friendly shell that is designed to be easy to use and learn. It has a syntax highlighting the feature and supports auto-suggestions, making it popular among new users.

  • Syntax highlighting: Fish includes syntax highlighting, which makes it easier to read and understand scripts by displaying different parts of the code in different colors.
  • Auto-suggestions: Fish supports auto-suggestions, which offer suggestions for completing commands as the user types them.
  • User-friendly syntax: Fish has a user-friendly syntax that is designed to be easy to learn and use.
  • Tab completions: Fish supports tab completions for commands, options, and arguments.

4. Ksh Shell

Ksh, or the Korn Shell, is a shell developed by David Korn at Bell Labs. It is known for its command history feature, which allows users to easily access and execute previous commands.

  • Command history: Ksh includes a command history feature that allows users to easily access and execute previous commands.
  • Aliases: Ksh allows users to create aliases for frequently used commands, which can save time and improve efficiency.
  • Functions: Ksh supports the creation of functions, which are reusable blocks of code that can be called from multiple places in a script.
  • Array variables: Ksh supports array variables, which allow users to store and manipulate multiple values in a single variable.

5. Csh Shell

Csh, or the C shell, is a shell that was developed at the University of California, Berkeley. It is similar to the C programming language and is known for its syntax and control structures.

  • Syntax and control structures: Csh is based on the C programming language, and its syntax and control structures are similar to those of C.
  • Aliases: Csh allows users to create aliases for frequently used commands, which can save time and improve efficiency.
  • Command history: Csh includes a command history feature that allows users to easily access and execute previous commands.
  • Job control: Csh supports job control, which allows users to run processes in the background, interrupt them, and resume them.

6. Dash Shell

Dash, or the Debian Almquist Shell, is a lightweight and fast shell that is designed to be used as the default shell on Debian-based systems. It is known for its minimalism and speed, and is often used in scripts and other automated tasks.

  • Lightweight and fast: Dash is a lightweight and fast shell that is designed to be used as the default shell on Debian-based systems.
  • Portable: Dash is portable and can be easily compiled on a wide range of systems.
  • Suitable for scripts: Dash is often used in scripts and other automated tasks due to its speed and minimalism.

7. Tcsh Shell

Tcsh, or the TENEX C shell, is a shell that is based on the C shell and includes additional features such as command line editing and programmable completion.

  • Command line editing: Tcsh includes command line editing features, such as the ability to use the left and right arrow keys to move the cursor, and the CTRL-R key to search the command history.
  • Programmable completion: Tcsh supports programmable completion, which allows users to customize the way command completions are displayed and triggered.
  • Aliases: Tcsh allows users to create aliases for frequently used commands, which can save time and improve efficiency.

8. Ash Shell

Ash, or the Almquist Shell, is a lightweight and portable shell that is often used in embedded systems and other resource-constrained environments.

  • Lightweight and portable: Ash is a lightweight and portable shell that is often used in embedded systems and other resource-constrained environments.
  • Suitable for scripts: Ash is often used in scripts and other automated tasks due to its small size and minimalism.
  • POSIX compliance: Ash is compliant with the POSIX shell specification, which makes it suitable for use in scripts that need to be portable across different systems.

9. Psh Shell

Psh, or the Public Domain Korn Shell, is a fork of the Korn shell that includes additional features and improvements. It is known for its portability and compatibility with other shells.

  • Command history: Psh includes a command history feature that allows users to easily access and execute previous commands.
  • Aliases: Psh allows users to create aliases for frequently used commands, which can save time and improve efficiency.
  • Functions: Psh supports the creation of functions, which are reusable blocks of code that can be called from multiple places in a script.
  • Portability: Psh is designed to be portable and can be easily compiled on a wide range of systems.

10. Xonsh Shell

Xonsh is a Python-based shell that combines the features of multiple shells and adds additional features such as syntax highlighting and tab completion. It is known for its flexibility and integration with other Python tools.

  • Python-based: Xonsh is a Python-based shell that allows users to use Python syntax and libraries in the shell.
  • Syntax highlighting: Xonsh includes syntax highlighting, which makes it easier to read and understand scripts by displaying different parts of the code in different colors.
  • Tab completions: Xonsh supports tab completions for commands, options, and arguments.
  • Integration with other tools: Xonsh can be integrated with other Python tools and libraries, allowing users to leverage their capabilities in the shell.

Wrap Up

These are some of the most popular open-source Linux shells available today. Each shell has its own set of features and characteristics, and the right shell for a specific task will depend on the needs and preferences of the user.

The post 10 Most Popular Open Source Linux Shells appeared first on TecAdmin.

]]>
https://tecadmin.net/most-popular-open-source-linux-shells/feed/ 0
How to Create Bash Aliases with Parameters https://tecadmin.net/how-to-create-bash-aliases-with-parameters/ https://tecadmin.net/how-to-create-bash-aliases-with-parameters/#respond Tue, 03 Jan 2023 08:34:12 +0000 https://tecadmin.net/?p=33217 Bash aliases are shortcuts that allow you to use a shorter or simpler command to represent a longer or more complex command. Bash aliases are useful when you frequently use long or complex commands and want to save time and effort by using a shorter or simpler command instead. To create a Bash alias with [...]

The post How to Create Bash Aliases with Parameters appeared first on TecAdmin.

]]>
Bash aliases are shortcuts that allow you to use a shorter or simpler command to represent a longer or more complex command. Bash aliases are useful when you frequently use long or complex commands and want to save time and effort by using a shorter or simpler command instead. To create a Bash alias with arguments and parameters, you can use the alias command and include variables in the alias definition.

In this article, we will explore how to create Bash aliases with arguments and parameters.

Creating a Bash Alias

You can use the `alias` command for creating aliases in your Linux system.

alias alias_name='command'

Here `alias_name` is the name of the alias, and `command` is the command that you want to alias.

For example, consider the following command:

ls -l /var | grep "^d" 

This command lists the directories in the `/var` directory in a long format and filters the output to show only the directories.

To create an alias for this command, you can use the following `alias` command:

alias lsdir='ls -l /var | grep "^d"' 

This will create an alias named `lsdir` that represents the original command. To use the alias, you can simply type `lsdir` at the command prompt, and the original command will be executed.

Creating Bash Alias with Arguments

Bash aliases do not accept arguments, but we can create a function that will accept the command line parameters. These functions can be used as aliases in your Linux system. For example, consider the following function definition:

lsdir(){ ls -l $1 | grep "^d"; } 

This alias definition creates an alias named `lsdir` that takes an argument ($1) representing the directory to list. To use this alias, you can pass the directory as an argument when you invoke the alias. For example:

lsdir /var 

This will list the directories in the `/etc` directory in long format and filter the output to show only the directories.

How to Create Bash Aliases with Parameters
Creating a Bash Alias with Parameters

Setup Permanent Bash Aliases

To make the alias permanent, you can add the alias command to your `~/.bashrc` file. This will ensure that the alias is available every time you start a new Bash session.

vim ~/.bashrc 

Append the following script at end of the script.

lsdir(){
        ls -l $1 | grep "^d";
}

How to Create Bash Aliases with Parameters
Create Permanent Bash Alias with Parameters

Then source the `~/.bashrc` configuration to update the current shell environments.

source ~/.bashrc 

It is important to note that Bash aliases are not the same as Linux commands, and they are not recognized by other programs or shells. If you want to use the alias in a script or in another shell, you will need to define the alias in that script or shell as well.

Conclusion

In conclusion, Bash aliases are useful when you frequently use long or complex commands and want to save time and effort by using a shorter or simpler command instead. To create a Bash alias with arguments and parameters, you can use the alias command and include variables in the alias definition. This allows you to pass arguments and parameters to the alias when you invoke it. To make the alias permanent, you can add the alias command to your ~/.bashrc file. However, it is important to note that Bash aliases are not the same as Linux commands, and they are not recognized by other programs or shells. If you want to use the alias in a script or in another shell, you will need to define the alias in that script or shell as well.

The post How to Create Bash Aliases with Parameters appeared first on TecAdmin.

]]>
https://tecadmin.net/how-to-create-bash-aliases-with-parameters/feed/ 0
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 Customize Bash Prompt (PS1) In Linux https://tecadmin.net/how-to-customize-bash-prompt-ps1-in-linux/ https://tecadmin.net/how-to-customize-bash-prompt-ps1-in-linux/#respond Wed, 21 Dec 2022 06:19:35 +0000 https://tecadmin.net/?p=22778 In Linux, PS1 is an environment variable that specifies the format of the command prompt displayed in the terminal. It stands for “Prompt String 1” and it is used to customize the appearance of the prompt. By default, the bash prompt includes the current username, hostname, and current working directory, followed by the `$` symbol [...]

The post How To Customize Bash Prompt (PS1) In Linux appeared first on TecAdmin.

]]>
In Linux, PS1 is an environment variable that specifies the format of the command prompt displayed in the terminal. It stands for “Prompt String 1” and it is used to customize the appearance of the prompt.

By default, the bash prompt includes the current username, hostname, and current working directory, followed by the `$` symbol for a regular user or the `#` symbol for the root user. The prompt is displayed on the command line, and it indicates that the terminal is ready for input.

You can customize the bash prompt by modifying the value of the PS1 variable. For example, you can use special characters and codes to change the colors, font styles, and other formatting options of the prompt. You can also include other information, such as the current time or the git branch name, in the prompt.

In this tutorial, we will discuss how to change the PS1 bash prompt and make is colorful in Linux.

Change Bash Prompt (PS1) in Linux

To customize the bash prompt (PS1) in Linux, you can use the following steps:

  • Open the `~/.bashrc` file in a text editor. This file is located in your home directory and contains configuration settings for the bash shell.
  • Find the line that sets the value of `PS1`. It will look something like this:

    PS1='[\u@\h \W]\$ '

    Check the below screenshot:

    How to Change PS1 Prompt in Linux

  • Modify the value of PS1 to customize the appearance of the prompt. You can use the following special characters to include information in the prompt:
    • `\u`: The username of the current user
    • `\h`: The hostname up to the first .
    • `\H`: The full hostname
    • `\w`: The current working directory
    • `\W`: The basename of the current working directory
    • `\$`: This code represents the prompt symbol, which is $ for a regular user and # for the root user.
  • For example, to customize the prompt to display the current working directory and the $ symbol, you could use the following value for PS1:

    PS1='\w \$ '

    Check the below screenshot:

    Changing PS1 Prompt in Linux

  • Save the `~/.bashrc` file and exit the text editor.
  • Run the following command to apply the changes to your current session:
    source ~/.bashrc 
    

Your bash prompt will now be customized according to the value you set for PS1.

Make Colorful Bash Prompt (PS1) in Linux

To customize the bash prompt (PS1) in Linux, you can use special characters and codes to add colors and other formatting options.

Here’s an example of a bash prompt that includes a red username, a green hostname, and a blue current working directory:

PS1='\[\e[0;31m\]\u\[\e[m\] \[\e[0;32m\]\h\[\e[m\]@\[\e[0;34m\]\w\[\e[m\]\$ '

To set the bash prompt in your current session, you can simply copy and paste the above code into the terminal and press Enter. To make the change permanent, you can add the same line to the .bashrc file in your home directory.

How to Make Colourful PS1 Prompt in Linux

Here’s a breakdown of the different color codes used in the example above:

  • \[\e[0;31m\] – This code sets the text color to red. The 0;31 value specifies the color, with 31 representing red.
  • \[\e[0;32m\] -This code sets the text color to green. The 0;32 value specifies the color, with 32 representing green.
  • \[\e[0;34m\] -This code sets the text color to blue. The 0;34 value specifies the color, with 34 representing green.
  • \[\e[m\] – This code resets the text color to the default value. So the remaining text will be default in color.

You can use other codes to customize the bash prompt with different colors and formatting options. For example, to make the text bold, you can use \[\e[1m\] before the text and \[\e[m\] after the text. You can find a list of all the available codes in the PROMPTING section of the bash man page.

I hope this helps! Let me know if you have any questions.

The post How To Customize Bash Prompt (PS1) In Linux appeared first on TecAdmin.

]]>
https://tecadmin.net/how-to-customize-bash-prompt-ps1-in-linux/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
Bash – Sending Email via Amazon SES https://tecadmin.net/bash-sending-email-via-amazon-ses-smtp/ https://tecadmin.net/bash-sending-email-via-amazon-ses-smtp/#respond Tue, 11 Oct 2022 04:13:55 +0000 https://tecadmin.net/?p=32093 Amazon SES (Simple Email Service) is a popular SMTP service provider similar to Sendgrid, Mailchimp, etc. In order to use SES, you need to signup for an Amazon Web Services account. Which is the leading Cloud-based service provider. Post signup you need to add your credit card for the billing. The default SES allows sending [...]

The post Bash – Sending Email via Amazon SES appeared first on TecAdmin.

]]>
Amazon SES (Simple Email Service) is a popular SMTP service provider similar to Sendgrid, Mailchimp, etc. In order to use SES, you need to signup for an Amazon Web Services account. Which is the leading Cloud-based service provider. Post signup you need to add your credit card for the billing. The default SES allows sending 2000 emails/day freely. After the default limit, you will be charged as pay-per-use.

In this blog post, you will learn to send emails via Amazon SES or any other SMTP provider from a bash shell or script.

Pre-Requisiteis

  • In this tutorial, we used the SendEmail command line SMTP client for sending emails. So you must have installed SendMail on your system.
  • You must have verified the email address or the domain name under Verified Identities in Amazon SES. When the domain is verified, you can use any email address while sending emails
  • All the new accounts in the Amazon SES are in sandbox mode for security purposes. You need to submit a request to support converting the SES account to production mode.

Shell Script for Sending Emails via SMTP

I have written a small shell script that sends emails via the remote SMTP servers. It uses the SendEmail SMTP client. Use any of the popular SMTP providers (like Sendgrid, Amazon SES, and Mailchimp) with this shell script. You can also integrate this shell script code into your existing shell scripts for sending emails properly.

#!/usr/bin/env bash

## SMTP configuration details

SMTP_HOST="email-smtp.us-east-1.amazonaws.com"
SMTP_PORT="587"
SMTP_USER="XXXXXXXXXXXXXXX"
SMTP_PASS="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
EMAIL_FROM="notification@example.com"
EMAIL_TO="your-email@example.com"

SUBJECT="WARNING: Github Public Repo Found"

## Sending email

cat Mailcontent.txt | sendemail -l /tmp/email.log \
    -f ${EMAIL_FROM} \
    -u ${SUBJECT} \
    -t ${EMAIL_TO}  \
    -s ${SMTP_HOST}:${SMTP_PORT}  \
    -o tls=yes  \
    -xu ${SMTP_USER}  \
    -xp ${SMTP_PASS}

In the above script, the Mailcontent.txt file contains the mail body content.

Conclusion

Shell scripts are an important part of system administration. It helps us to automate tasks quickly like scheduling backups, archiving logs and collecting data, etc. Sometimes we are also required to send emails from shell scripts. In this tutorial, you have learned to send emails via the Amazon SES server. Even you can also use this script with any other SMTP providers.

The post Bash – Sending Email via Amazon SES appeared first on TecAdmin.

]]>
https://tecadmin.net/bash-sending-email-via-amazon-ses-smtp/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 Correctly Set the $PATH variable in Bash https://tecadmin.net/setting-up-path-environment-variable-in-bash/ https://tecadmin.net/setting-up-path-environment-variable-in-bash/#respond Wed, 03 Aug 2022 12:19:38 +0000 https://tecadmin.net/?p=30798 Bash is an acronym of Bourne-Again Shell, which is the successor of Bourne Shell distributed with most of the Linux and GNU operating systems. It comes with multiple advanced features from the previous version. The PATH is an environment variable that stores the directories path containing the executable files. How to Set PATH Variable? Whenever [...]

The post How to Correctly Set the $PATH variable in Bash appeared first on TecAdmin.

]]>
Bash is an acronym of Bourne-Again Shell, which is the successor of Bourne Shell distributed with most of the Linux and GNU operating systems. It comes with multiple advanced features from the previous version.

The PATH is an environment variable that stores the directories path containing the executable files.

How to Set PATH Variable?

Whenever you need to add a new executable in the PATH variable, you can either add it to the start of another directory or at the end of other directories.

The system checks for any executable under directories set in PATH from start to end. If the required binary is found in a directory, it will ignore the rest. In case, you have added an executable at the end, the system may ignore that if an executable is found with the same name in previously configured directories.

  • Setting up after other executables:
    export PATH=${PATH}:/opt/maven/bin
  • Setting up before other executables:
    export PATH=/opt/maven/bin:${PATH}
Info: When using the /etc/environment file, just set the path without export command, like:
PATH=/opt/maven/bin:${PATH}

Where to Set the PATH Variable?

There are multiple scripts available in the Linux system where you can set the PATH environment variable. These scripts are executed in predefined conditions. Like, some scripts are executed during system startup, and some of them are executed at user login or logout.

Below is the list of scripts that are executed under different conditions. You can choose one of them to set the PATH variable.

  • System-wide Configuration:
    • /etc/bashrc: This script is invoked at system startup. Setting the PATH environment to this file will be available for all users.
    • /etc/bash.bashrc: This script is invoked for the interactive and login shells.
    • /etc/profile: This script is invoked with login shells only.
    • /etc/profile.d/*.sh: All the script with “.sh” extension are invoked by /etc/profile script.
    • /etc/environment: This is the first file that operating system uses at login. This is specifically used for setting up environment variables. This file doesn’t require to use “export” keyword.

  • User level configuration:
    • $HOME/.bashrc: This file is invoked for non-login shell.
    • $HOME/.profile: This file is invoked for the login shell. Also, this file invokes the ~/.bashrc script.

Conclusion

The PATH environment variable is a necessary part of the Linux and other GNU-based operating systems. You must be careful before setting up the PATH variable.

The post How to Correctly Set the $PATH variable in Bash appeared first on TecAdmin.

]]>
https://tecadmin.net/setting-up-path-environment-variable-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
Convert String to Lowercase in Bash – Easier Than You Think https://tecadmin.net/convert-string-to-lowercase-in-bash/ https://tecadmin.net/convert-string-to-lowercase-in-bash/#respond Mon, 01 Aug 2022 10:03:47 +0000 https://tecadmin.net/?p=30813 Question: How do I convert all the characters to the lowercase of a string in the bash shell script? In Linux, the tr command is used to translate, squeeze, and/or delete characters. So with the help of the tr command, you can convert the case of any character. You can do this quickly with a [...]

The post Convert String to Lowercase in Bash – Easier Than You Think appeared first on TecAdmin.

]]>
Question: How do I convert all the characters to the lowercase of a string in the bash shell script?

In Linux, the tr command is used to translate, squeeze, and/or delete characters. So with the help of the tr command, you can convert the case of any character. You can do this quickly with a single-line command.

You can use the following command to convert a string to lowercase. Here the command takes the standard input of a string and processes it.

echo "Input string here" | tr '[:upper:]' '[:lower:]' 

Let’s discuss with an example.

Example

Let’s create a sample shell script. Initialize a variable with a string having a few uppercase letters. Then convert all the letters to lowercase and store them in another variable.

#!/usr/bin/env bash

str="Hello World"
lowerStr=$(echo "$str" | tr '[:upper:]' '[:lower:]')

echo "Input String: $str"
echo "Result String:  $lowerStr"

Run the above script and see the results:

Output:
Input String: Hello World Result String: hello world

You can see the result string has all the characters in lowercase.

The post Convert String to Lowercase in Bash – Easier Than You Think appeared first on TecAdmin.

]]>
https://tecadmin.net/convert-string-to-lowercase-in-bash/feed/ 0