BASH Programming – Linux Hint https://linuxhint.com Exploring and Master Linux Ecosystem Wed, 10 Mar 2021 03:37:00 +0000 en-US hourly 1 https://wordpress.org/?v=5.6.2 Bash Printf command https://linuxhint.com/bash-printf-command/ Tue, 09 Mar 2021 04:17:47 +0000 https://linuxhint.com/?p=93380 Working with bash scripting, we mostly use the “echo” command to print any output, which is convenient and easy to use and fulfills the requirement most of the time. But simplicity comes with limitation; echo command has its own limitation when it comes to formatting the output, in that case, “printf” command play its role.

The “printf” command in bash scripting works the same way “printf ()” works in the C language. This post will focus on the “printf” command, its syntax, and examples that further elaborate the use of this command. Let’s check the syntax of the “printf” command:

printf <var> <formate> <arguments…>

<var> : It is optional to assign output to a variable.
<formate> : It is a string that may contain different format specifiers such as “%s”, “%b”, “%d”, “%f”, and backslash escape
<arguments…> : The arguments can be any value or variable

How to use printf command in bash scripting using Vim editor:

We are using Vim editor for this guide because of its rich functionality and ease of use. Get Vim on your device using:

$ sudo apt install vim

Launch vim editor:

$ vim

Let’s write a simple program to print a string using “printf”:

#! /bin/bash
printf “Hello Linuxhint”

To save the file, press the “Esc” button to switch the mode and then type “:w example.sh” and then “Enter”. Now open a new terminal window and type:

$bash example.sh

The above command will execute the script the print out “hello linuxhint” text as shown below:

Now, let’s include some format specifiers:

#! /bin/bash
printf%s\n” “Hello Linuxhint”

In the above example, “%s” tells that the corresponding argument should be treated as string and “\n” for the new line. Similarly, if we use “%d,” then the argument will be treated as an integer:

#! /bin/bash
printf%s\n” “Hello Linuxhint” “Learn about” “Linux”

All three arguments will be treated as a string and printed in a new line as demonstrated in the following output:

Another example is mentioned below further to understand the use of the “printf” command:

#! /bin/bash
echo “Enter your name”
read name
echo “Enter your age”
read age
printf  “Your name : %s\nYour age : %s\n” “$name” “$age

“Your name : %s\n Your age : %s\n ” is format while “$name” “$age” are the arguments. Whereas “%s” pointing the arguments.

How to use conversion specifiers with printf command:

The conversion specifiers are characters used with the “%” sign to indicate how to treat the arguments. Let’s check the list of some commonly used specifiers:

Specifier Description
%% Prints “%” symbol
%c Takes arguments as a single character
%e and %E Take argument in floating-point number and prints in exponential notation, %e for lower case letter and %E for capital letter
%g and %G Take argument in floating-point number and prints in normal or exponential notation
%f Takes argument as floating numbers
%d Takes arguments as signed integers
%u Takes argument as unsigned integers
%o Takes argument as an unsigned octal number
%x and %X Takes arguments as unsigned hexadecimal integers

Let’s further elaborate the above specifiers with an example in bash:

#! /bin/bash
echo “Enter a number to convert”
read number
printf  “Decimal : %d\nOctal : %o\nHex : %X\n” “$number” “$number” “$number

How to use Flag, Width, and Precision directives with printf command:

Flag directives come with optional use with the “printf” command. The commonly used flag directives are

  • “-” Left justify the output
  • “+” Adds “+” sign with integer
  • “0” Adds “0” with a number instead of spaces

Width directives add space with the output usually used after the flag. Let’s understand it with an example:

#! /bin/bash
echo “Enter your name”
read name
echo “Enter your age”
read age
printf “You name and age are: %5s %5d\n” “$name” “age”

“%30s” means space is 30 characters long, and to align the output form left, use the “-” sign “%-30s”.

The precision directive consists of the dot “.” Following by positive integer:

#! /bin/bash
printf%.2f” 2.56473

The output would be:

If the number is an integer, the precision directive will add “0” before the number. If the number is floating-point type, then the precision directive will specify the number of positive digits after the decimal point. For string, it specifies the number of characters to be displayed:

#! /bin/bash
printf%.2f\n” 2.468936
printf%.3d\n” 10
printf%.3s\n” “samlinux”

Backslash Escaped parameters:

Backslash escape parameters, also called escape sequences, are used with a backslash to format the string with the “printf” command. These sequences do not represent themselves but interpret in some other characters. Some commonly used escape sequences are:

Character Description
\\ Prints backslash character
\b Prints backspace character
\n Prints output in a new line
\r Prints a carriage return (cursor at the beginning of the line)
\t Gives tab space from right
\v Gives tab space

Conclusion:

When it comes to print something in bash scripting, the “echo” command is most commonly used because it is easy to use and remember. But “echo” command has its limitation. Therefore, to properly format the output, the “printf” command can be used. The “printf” command comes with plenty of options to format string output and even basic numbers’ conversions and formatting. This guide thoroughly comprehends the “printf” command’s functionality in bash scripting with examples. ]]> Bash if-else statements https://linuxhint.com/bash-if-else-statements/ Tue, 09 Mar 2021 03:30:35 +0000 https://linuxhint.com/?p=93369 In your day-to-day life, many things are associated with conditions. For example, when we decide, we first analyze its conditions, outcomes and finalize the decision. Conditional statements in any programming language shadow the same way, and they are core to every language. These statements are used to manage code execution flow and perform tasks based on true and false conditions.

The above chart is demonstrating the execution of the conditional statement. In programming jargon, we use the “if” word with a condition and specify the condition’s outcomes upon being true and false. Let’s check the basic syntax of a conditional statement in bash:

if [Condition]
then
    <Statement>
fi

if: Indicates the condition to be applied
then: If the condition is true, then execute the <statement>
fi: Closes the if statement

Let’s thoroughly understand the conditional statements with examples:

Bash if…then Example:

For this guide, we are using Vim editor; install it by executing the following command:

$ sudo apt install vim

Once the download and installation are finished, launch Vim editor in the terminal by typing:

$ vim

The basic if…then the example is given below:

#! /bin/bash
echo “Enter a number”
read number
if [ $number -lt 100 ]
then
echo “Your entered number is less than 100
fi

The above program is getting input from the user through the “read” command; the if statement is checking if the entered number is less than 100 or not. If the entered number is less than 100, then the “echo” statement will be executed; otherwise, the program will not give any output. In the next example, we will check how to get an output if the condition fails:

Bash if…then…else Example:

In the above example, if the condition is true, then the echo statement will be executed, now we will add “else” to get output when the “if” condition fails:

#! /bin/bash/
echo “Enter a number”
read number
if [ $number -lt 100 ]
then
echo “Your entered number is less than 100
else
echo “Your entered number is greater than 100
fi

Bash Nested if statement (if Elif):

To add more than one condition in the program, we use nested if statements. Let’s understand the nested if concept through an example:

#! /bin/bash/
echo “Enter a number from 1-20
read number
if [ $number -lt 10 ]
then
echo “Your entered number is less than 10
elif [ $number -le 20 ]
then
echo “Your entered number is greater than 10
else
echo “You entered number is not between 1-20
fi

The above code is demonstrating how to use nested if. The compiler will check both if and elif conditions and execute the statement satisfying the condition. The program will execute the “else” statement if both conditions are false.

Using multiple conditions with if…else:

To use multiple conditions with one if statement, we can use conditional operators:

  • AND operator “&&” execute “then” statement if all conditions are true
  • OR operator “||” execute “then” statement if any of the conditions are true

Let’s understand it with an example:

#! /bin/bash/
echo “Enter a number from 1-10
read number
if [ $number -ge 1 ] && [ $number -le 10 ];
then
echo “Your entered number greater than 1 and less than 10
else
echo “Your number is not between 1-10
fi

“then” statement will be executed when both conditions are true. In the above example, any number greater than 1 and less than 10 will satisfy both conditions.

#! /bin/bash/
echo “Enter a number”
read number
if [ $number -le 10 ] || [$number-le20];
then
echo “You have entered the correct number”
else
echo “Your entered the incorrect number”
fi

“then” statement will execute when either of the conditions is true. Any number that is less than 10, and 20 will be termed as a correct number greater than 20 will be incorrect because both conditions are not true.

Conclusion:

Like many other programming languages, bash scripting also uses conditional statements. If-else statement is a key part of any computer programming language. It helps to perform various functions based on the condition applied. This post thoroughly focuses on the conditional statement in bash scripting, its syntax, and various use of conditional statements with examples. It is one of the essential concepts for any developer to learn because these statements are building blocks of any algorithm.

]]>
How to Use the read Command in Bash https://linuxhint.com/use-read-command-bash/ Mon, 08 Mar 2021 04:14:29 +0000 https://linuxhint.com/?p=93389 In Bash scripting, the “read” command is used to obtain input from users. Understanding the “read” command is key to making your code more interactive. The “read” command is used to obtain inputted information from the user. This article shows you how to use the “read” command in Bash to interact with users.

First, check out the basic syntax of the “read” command:

read [option] variable

Using the “read” command means that you are interacting with Bash to obtain information from the user. It saves the value in a variable, but with no “$” sign. You will be able to better understand this concept with an example.

Example 1: Using the “read” Command in a Bash Script

To examine the “read” command more in-depth, we will create a simple script that will ask for the user’s name. First, open any text editor; for this tutorial, I am using the Vim text editor due to its many useful features. To install Vim, execute the following command in the terminal:

$sudo apt install vim

Next, type the following in the text file:

#! \bin\bash

echo “Please type your name”

read name

echo “Your name is” $name

Save the file by any name, then press Esc and type “:w readcom.sh.” To run the script, issue the following command:

$ bash readcom.sh

The above script will ask the user to write his/her name. The “read” command will then save the input from the user. The next line will print the name that the user input.

Example 2: Simplifying Code Using the “prompt” Operator

The above example can be simplified further using the “prompt” operator. Let us re-write the above example to comprehend the code:

#! /bin/bash

read –p “Please type your name” name

echo “Your name is” $name

Example 3: Hiding the User Input Using the “secret/silent” Operator

The “-s” flag can be used to hide the input of the user. The following Bash script example shows you how to use the “-s” operator:

#! /bin/bash

read –p “Please type your username” username

read –s –p “Please type your password” $password

Example 4: Limiting the Character Length

The “-n” flag can be used to add a constraint to the number of characters that the user may input.

#!/bin/bash

read –n 8 –p “Please type your username not exceeding 8 characters” username

echo “Your username is” $username

With the “-n” option, the user can still write less than eight characters. To further restrict the input length, the “-N” flag can be used, which limits the user’s response to exactly eight characters.

Example 5: Getting the Input in an Array

The user input can also be taken in an array with the “-a” flag. For instance, to get the user’s name, age, and email address in one go, then we can use an array. Let us look at an example:

#! /bin/bash

echo “Please type your name, age, and email”

read –a array name age email

echo “Your name, age, and email address are: ${array[@]} name age email”

echo “Your name and age are: ${array[@]:0:1} name age”

echo “Your email address is: ${array[2]} email”
  • “${array[@]}” will loop through all variables.
  • To iterate through the indexes 0 to 1, use “${array[@]:0:1}” with the variable names.
  • To obtain the value of a particular variable at a specific index, use “${array[2]}” with the variable name.

Example 6: Adding a Timeout to the “read” Command

As the name of the command indicates, a timeout can be added as a condition of reading the code using the “-t” flag, which makes the user enter information for a specific time. Otherwise, the program will move to the next line of code.

#! \bin\bash

echo “What is the capital of Japan? Answer in 5 seconds”

echo –t 5 answer


if [$answer” = “tokyo” ] || [$answer” = “Tokyo” ];

then

echo “Your answer is Correct!

else

echo “Your answer is Wrong!

fi

Conclusion

Getting input from a user input is one of the most important parts of programming, making your programs more interactive. This article showed you how to use the “read” command, one of the key commands in Bash scripting. In this article, you learned about some of the various approaches that you can use with the “read” command, from basic flag operators to advanced operators.

]]>
How to Customize a Bash Shell with the shopt Command https://linuxhint.com/how-to-customize-a-bash-shell-with-the-shopt-command/ Sun, 07 Mar 2021 23:13:45 +0000 https://linuxhint.com/?p=93204

Shopt is a built-in command in Unix-like operating systems, such as macOS and Linux distributions. The “shopt” command provides control over many settings that are used to tweak the operations in a Bash shell.

This article shows you how to work with the “shopt” command in Linux. Since this command is built-in, it is not required to install this command to use it. The number of options available for the “shopt” command varies from version to version; older versions will have fewer commands compared to newer versions.

Some options in Bash are enabled or disabled by default, but these options can temporarily be tweaked, once you restart the shell, these options will be reverted. However, it is also possible to permanently change these options if you are interested in keeping a tweaked version of the shell.

First, let us look at the basic syntax of the “shopt” command:

$ shopt [s[-p] [-q] [-s]] [optname…]
Options Description
-s Set [optname…]
-u Unset [optname…]
-p Show list of all settable [optname…]
-q Indicate status of [optname…]
-o Restrict values of [optname…] to be those defined for the “-o” to be built-in.

We will now thoroughly discuss the “shopt” command and its various options.

Checking Options with the shopt Command

To check all the options available for use with the “shopt” command, simply type “shopt” in the terminal, as follows:

$ shopt

All these options can also be presented in the form of columns. To do so, enter the following command:

$shopt | column

Finding shopt in Linux

Use the following command to print the Bash manual:

$man bash

Then, issue the command provided below:

/assoc_expand_once

This will provide a detailed overview of the available “shopt” options.

Enabling and Disabling “shopt” Command Options

To enable and disable the options associated with the “shopt” command, use “-s” to set and “-u” to unset/disable any option. As discussed previously, some of the options will already be enabled and disabled by default. Enter the following command to check all enabled options:

$ shopt –s

To disable any enabled option, simply use the option name from the list. For example, you would use the following command to disable the “histappend” option:

$shopt –s histappend

To disable all options, issue the following command:

$shopt –u

To get the output in column form, use the command provided below:

$ shopt –s | column

Finally, to check disabled services in column form, use the following command:

$ shopt –u | column

Now, let us enable the “cmdhist” option. To do so, we will use the command provided below:

$shopt –u cmdhist

These changes can be verified using the “shopt” command with the “-s” and “-u” options. Next, we will discuss some other options associated with this command and their functionalities.

Enabling the “histverify” Option with the shopt Command

The “histverify” command executes a command from the command history immediately. This option is “off” by default, so, to check whether this option is enabled, issue the following:

$ shopt histverify

To enable this option, use the command provided below:

$ shopt -s histverify

Now that the history verification has been turned on, instead of immediately executing the command “histverify,” the command will be shown first for verification. For instance, if you type “!783” in the terminal, the output will first show the “783rd” command from the history before executing it.

To check the number of all commands in the history, type “history” in the terminal.

Enabling the “cdspell” Option with the shopt Command

Another option that you can use to modify the shell settings is the “cdspell” option. The “cdspell” option automatically corrects any spelling mistakes in the command. To enable this option, issue the following command:

$shopt –s cdspell

Now, you can change the directory with small letters, as well:

$ cd pictures

Enabling Escape Sequences with the “echo” Command

Another important setting to enable is the “xpg_echo” command. Enabling this command will allow the echo command to interpret escape characters, such as the “\n” and “\t” options.

To set this command, use the following:

$shopt –s epg_echo

To verify this command, issue the following:

$echo “Hello this is\n linuxhint.com”

How to Make Changes Permanent

So far, the changes we have made using the terminal are not permanent, but they can be made permanent via a simple command. Issue the following command in the terminal:

$gedit .bashrc

Upon execution of the above command, a file will open. Any shopt option can be included here to make the changes permanent, as shown in the images below:

Conclusion

This article showed you how to use the “shopt” command and how to modify the settings of this command. The “shopt” command can be used to enable and disable various settings of Bash to alter its default functionality. This command also contains many options, but it is not necessary to deal with every option, and many of them would probably not interest you. Most of the available “shopt” options are useful for older distributions only. Check out the Bash manual to learn more about each option discussed above, and decide which options make the most out of your experience.

]]>
How to Create Simple Shell Scripts in Linux Using Vim https://linuxhint.com/create-simple-shell-scripts-linux/ Sun, 07 Mar 2021 21:56:14 +0000 https://linuxhint.com/?p=93193

Shell Scripting executes commands to perform some useful functions and is designed to run in the shell. Shell scripts are quite handy to perform operations like file manipulation, automating tasks to avoid time consumption; you can even create your commands.

Shell is an interface between the user and operating system that lets users interact with the operating system and perform various tasks using commands. Shell takes input from the user through the terminal, interacts with the kernel, processes it, and gives the output.

How to create a shell script using Vim

Shell Scripts usually created using any text editor. Nano and Vim editors are well-known text editors to create bash scripting files.  For this example, we are using “Vim”. If you do not have Vim, then install it using the command:

$ sudo apt install vim

Open text editor using:

$ vim

Create a new file:

$ vi testscript.sh

Type the script. “#! /bin/bash” operator, shell directed to bourne shell: r

#! /bin/bash

echo “Hello World”

And save the file, press the “Esc” key to switch the mode, and then press “:w” to save it. If it gives a “Read-only” error file, then use “:w!”, the file will be saved:

Now to execute the file, type:

bash test script. sh

How to add comments in a shell script

To add a comment, use the “#” operator; the syntax is given below:

#! /bin/bash

#This is my first shell script

echo “Hello World”

How to use variables in a shell script

For any programming, language variables are essential. Variables are used to store a value, whether it is an integer, character, or text string. Let’s understand it with an example:

#! /bin/bash

myvariable=“This is my first script”

echo $myvariable

The above script will give variable value as output:

Let’s check how to get value in a variable from user value from user:

#! /bin/bash

echo “Enter your name”

read name_varable

echo "Enter your age"

read age_variable

echo$name_varibale is $ age_variable old”

The following image is showing the output:

Conclusion

Shell scripting is very important to create your own command or run multiple commands with one script file to perform various functions. In this guide, we grasp the basic idea of shell scripting. We learned how to script and a shell script file, save it and then execute it. Moreover, we understood the usage of variables in shell scripting. Shell scripting is very handy to accomplish different useful tasks, and there is a lot to uncover.

]]>
Shebang Bash: Explained with Examples https://linuxhint.com/shebang-bash-explained-in-examples/ Fri, 05 Mar 2021 10:47:54 +0000 https://linuxhint.com/?p=92899 Bash is a command language interpreter. Many operating systems incorporate bash as the default command interpreter, especially most of the GNU/Linux systems. Bash scripting is a method of automating a set of commands that would otherwise be executed interactively one-by-one.

In this guide, check out what shebang bash is and how to use it.

Shebang Bash:

In bash scripting, Shebang is a way to declare what interpreter the operating system will use to parse the rest of the file. The Shebang is characterized by the set of characters “#!” (without quotes).

Here’s a quick breakdown of the Shebang interpreter directive.

#!<interpreter> [arguments]

For example, if a script is to be parsed using the Bash shell, then the Shebang interpreter directive would look like this.

#!/bin/bash

The Shebang interpreter directive has certain properties.

  • It must be the first line of the script.
  • It must start with a shebang (#!).
  • There may or may not be whitespace after the shebang (#!).
  • The interpreter will be the full path to a binary file.
  • There may or may not be interpreter arguments.

Here’s a shortlist of some of the most common Shebang interpreter directives.

  • #!/bin/bash: The script will be parsed using bash.
  • #!/usr/bin/python: The script will be parsed using the python binary.
  • #!/usr/bin/env perl: The script will be parsed using the perl executable. The location of the perl executable will be provided by the env command.

Using Shebang Bash:

Scripts can have no Shebang bash. Any such script will be parsed using the default interpreter. For example, bash is the default interpreter for bash and sh for zsh. While most of the UNIX/Linux systems have bash as the default, users have options to use others. In such a scenario, without declaring the interpreter, the script may not perform its preferred task.

There are two methods of using the Shebang directive to declare the interpreter. The first one is to declare the file path to the executable.

#!/bin/bash

Another method is to use the env utility to locate the executable.

#!/usr/bin/env bash

The benefit of using the env utility is, it will look for the executable under the $PATH environment variable of the current user. In this example, env will look for the bash. If there is more than one bash executable declared in the $PATH variable, then the first one will be used.

As mentioned, Shebang bash also supports executable arguments. For example, to use bash with debug mode, the Shebang interpreter directive would look like this.

#!/bin/bash -x

When it comes to using env for the Shebang bash, adding an executable argument requires using the “set” option. For example, the following one will use bash with debug mode enabled.

#!/usr/bin/env bash
$ set -x

Script Example:

We’ve discussed the basics of Shebang bash. It’s time to put it into practice. Let’s have a look at the implementation of Shebang bash.

Launch the text editor of your choice and type the following script:

$ #!/bin/sh
$ echo "hello_world_bash"

Save the file. To run the script, it has to be marked as an executable. Run the following command:

$ chmod +x <script>

Run the script:

$ ./<script>

Not very difficult, right? Now, let’s try using the different Shebang bash expressions. Try the ones given below:

$ #!/usr/bin/env bash
$ set -x
$ echo "hello_world_bash_debug"

Overriding the Shebang Bash:

While the Shebang bash defines the interpreter to use, in certain situations, you may want to use a different interpreter. It’s possible to override the script-defined interpreter by explicitly specifying the interpreter to the shell.

For example, have a look at the following script:

$ #!/bin/sh
$ echo "hello_world_sh"

By default, it would be run using sh. To run it using bash, use the following method:

$ <interpreter> <script>

Note that for normal use cases just using the default sh or bash interpreter is good enough and overriding is not relevant.

Final Thoughts:

Shebang bash is a very simple concept. For bash scripting, it’s very important to understand and implement it.

Interested more in Bash scripting? Check out this beginner’s guide on how to write a simple bash script.

Happy computing!

]]>
How to Run the Same Command Multiple Times in Linux https://linuxhint.com/run-same-command-multiple-times-linux/ Tue, 23 Feb 2021 17:31:53 +0000 https://linuxhint.com/?p=91069 When programming, you may encounter a situation in which you need to perform the same task multiple times. A simple solution is to manually repeat the process as many times as it is needed; however, it is not productive to do so. That is why the concept of loops was introduced to programming. The basic goal of a loop is to repeat a task several times, depending upon the value provided for the iterator and the termination condition of the loop. Loops allow programmers to avoid the hassle of repeating processes manually.

Suppose that there is a command that you wish to run multiple times. There are several important reasons that you might need to run a command repeatedly, so you want to be sure that a certain command produces the correct output every time it is executed. The more you run a command manually, the more certainty you will gain each time you run the command.

But how do you do this programmatically? Well, there are several methods that can be used to run the same command multiple times, as well as for verifying the output of the repeated command. This article shows you how to create a repeatable command using Linux Mint 20 as the host operating system.

Methods for Reiterating Commands in Linux Mint 20

The following sections show you two methods that you can use to run the same command multiple times using a Bash script in Linux Mint 20.

Method 1: Reiterating a Command Using the “for” Loop in Bash

The first method of running the same command multiple times using a Bash script in Linux Mint 20 is implemented using the “for” loop. The sample script is shown in the following image. You can copy this script into any Bash file of your choice.

In this script, we have created a simple “for” loop that iterates through a list containing items from 1 to 5, meaning that the “for” loop will have a total of five iterations. In these five iterations, our desired command will be executed with each iteration, or five times.

Here, we specified for the “date” command to run “5” times. This command displays the current system date and time in the terminal. You can use any other command of your choice in place of the “date” command.

We also wanted our output to be displayed after every “1” second. To serve this purpose, we used the “sleep” command with a sleep interval of “1,” though you may increase the sleep interval according to your preferences. You can even increase or decrease the number of iterations of the “for” loop, depending upon the number of times you want to execute the command.

Execute this Bash script with the following command:

$ bash Multiple.sh

The result of the above Bash script is shown in the following image. The output contains the current system date and time at “5” different intervals, which means that our “date” command has been successfully executed for the specified number of iterations.

Method 2: Reiterating a Command Using the “while” Loop in Bash

The second method of reiterating a command multiple times using a Bash script in Linux Mint 20 is implemented using the “while” loop. The sample script is shown in the following image. You can copy this script into any Bash file of your choice.

In this script, the variable “i” is initialized with the value “0.” This variable will act as the iterator for the “while” loop. Then, the iterating condition of the “while” loop is that the value of the variable “i” is less than “5.” Within this loop, we have a “date” command that will serve the same purpose as the command used in Method 1.

This command is followed by the “sleep” command. This command prints the output after some specified interval, which is “1” second, in this case. Finally, we will increment the value of the iterator “i” using the “+1” incrementing notation.

The result of our Bash script is depicted in the following image. This output contains the current system date and time at five different intervals, meaning that the “date” command has been executed successfully for the specified number of iterations. This time, we have achieved this goal by implementing the “while” loop instead of the “for” loop.

Conclusion

Today, you learned that instead of manually running a command multiple times, you can write a Bash script to simplify this task. Using the “for” or “while” loops in a Bash script, you can easily achieve the functionality of running a command multiple times. This article showed you how to reiterate commands using both methods while running the “date” command repetitively. We also used the “sleep” command in both of our example scripts so that it was easier to visualize the effect of the repetitive “date” command since the value of “seconds” will change every time this command is executed.

In the same manner, you can run any command of your choice multiple times using either of the Bash scripts that we shared with you today while operating in Linux Mint 20. I hope this guide will help you to run the same command multiple times in Linux.

]]>
What Is BC in a Bash Script? https://linuxhint.com/what-is-bc-bash-script/ Tue, 23 Feb 2021 17:25:29 +0000 https://linuxhint.com/?p=91052 BC, which stands for Basic Calculator, is a command in Bash that is used to provide the functionality of a scientific calculator within a Bash script. This can be useful for scripting with various arithmentic use cases and scenarios. This article shows you how to use BC in a Bash script.

Examples of using the BC Command in a Bash Script

To learn more about using the BC command in a Bash script in Linux Mint 20, take a look at the examples provided in the following sections:

Example 1: Calculating the Power of a Number

Bash programming only allows us to perform mathematical operations on integers, i.e., you cannot perform calculations with decimals or floating-point numbers in Bash. To calculate the power of a decimal with an integer exponent, we will write the following Bash script:

In this Bash script, a one-liner echo command calculates the second power of “2.5.” The result is piped to the BC command, which will perform this calculation.

After saving this script, we can execute the following command:

$ bash BC.sh

The output of our Bash script results in a decimal number, as shown in the image below. This operation would not have been possible without the BC command.

Example 2: Checking Whether a Number is Less than Another Number

The BC command can also be used to compare if a number is greater or less than another. To draw such a comparison, we will write the following Bash script:

In this Bash script, again, a one-liner echo command is used. The command checks whether one number is less than another number. The result is piped to the BC command, which will perform this comparison. The output of this contrast will be “1” if the given statement is true; otherwise, the output will be “0.”

The output of the above Bash script is “0” since 10 is greater than 5, which makes our statement false. This output can be seen in the image below:

Example 3: Checking Whether a Number Is Equal to Another Number

As in Example 2, the BC command is used again in this example; however, this time, the command will check whether one number is equal to another number. To draw such a comparison, we will write the following Bash script:

In this Bash script, a one-liner echo command checks whether the first number is equal to the other number. The result is piped to the BC command, which will perform this comparison. The output of this script will be “1” if the given statement is true; otherwise, the output will be “0” if the statement is false.

The output of our Bash script is “1” since 2 is equal to 2, which makes our statement true. This output can be seen in the image below:

Example 4: Using the BC Command with the && Logical Operator

The BC command can also be paired up with logical operators in Bash, including && and ||, which correspond to logical multiplication and logical addition, respectively. The outcome of the && logical operator is true, or “1,” when all the provided inputs are non-zero. Otherwise, the result will be false, or “0.” To use the && operator with the BC command in Bash, we will write the following Bash script:

In this Bash script, a simple one-liner echo command performs the logical operation && between the numbers “10” and “0.” The result is piped to the BC command that will perform this operation.

The output of our Bash script is “0” since at least one of our provided values is not non-zero, which makes our operation false. This output can be seen in the image below:

Example 5: Using the BC Command with the || Logical Operator

The result of the || logical operator is true, or “1,” when one of the provided inputs is non-zero. Otherwise, the result will be false, or “0.” To use the || operator with the BC command in Bash, we will write the following Bash script:

In this Bash script, a simple one-liner echo command performs the logical operation || between two numbers, “10” and “0.” The result is piped to the BC command that will perform this operation.

The output of our Bash script is “1” since one of our provided values is non-zero, which makes our operation true. This output can be seen in the image below:

Example 6: Dividing Decimal Numbers with the Result in Decimal

We can also use the BC command to divide decimal numbers and return the result in decimal form, up to a specific decimal place. To obtain this decimal precision, we will write the following Bash script:

In this Bash script, a one-liner echo command divides two numbers, “6.5” and “2.7.” We want the result to be accurate to “3” decimal places, and we have used the “scale” flag for this purpose. The result is piped to the BC command that will perform this calculation.

The output of our Bash script results in a decimal number that is correct up to 3 decimal places, as shown in the image below. This would not have been possible without using the “scale flag” with the BC command. The output can be seen in the image below:

Conclusion

In this article, we provided several examples of using the BC command in Bash script in Linux Mint 20. However, there is still a lot more that you can do with this powerful command that you can explore on your own and add more math and calculations to your bash scripts.

]]>
How to fix “bash: /usr/sbin/ifconfig: No such file or directory” on Linux https://linuxhint.com/fix-ifconfig-command-not-found-linux/ Mon, 22 Feb 2021 16:06:45 +0000 https://linuxhint.com/?p=90286

You were trying to know the IP address of your Linux Operating System, and an error occurred with the message “bash: /usr/sbin/ifconfig: No such file or directory,” and that error has brought you here. Don’t worry; you are reading exactly the right post. But, the question arises that it was working before; what happened?

Why is the “ifconfig” command not working anymore?

The answer is pretty simple; the “ifconfig” command is deprecated in Linux Operating Systems’ upcoming versions. It must be an older version of your Operating System when this command worked for you last time. But, it does not mean you are out of doing anything. You can either know the IP address of your system by typing the command given below.

$ ip a

Or you can install the net-tools on your Operating System if you still want to run the “ifconfig” command.

How to install net-tools on Linux

The net-tools is a toolkit that provides many programs related to Linux networking and allows users to perform network-related tasks. For example,

  • Hostname configuration
  • Netstat tool
  • Address Resolution Protocol Configuration
  • Dig command
  • Ifconfig command

Let’s install the net-tools so that we can run the “ifconfig” command easily. This post will install the net-tools on Ubuntu 20.04 LTS operating System, but the process will be the same for Debian or other Debian-based systems.

Step 1: Update the system’s APT cache repository

First of all, before installing any application in a Linux operation system, it is a better practice to update the system’s APT cache repository first.

$ sudo apt update

After updating the system’s APT repository cache, install net-tools.

Step 2: Install net-tools

The command for installing net-tools on Ubuntu 20.04 is typed below.

$ sudo apt install net-tools -y

The installation of net-tools will start and complete in a couple of minutes.

After the installation of net-tools, you can run the “ifconfig” command.

Step 3: Run the “ifconfig” command

Now, run the “ifconfig” command in the terminal

$ ifconfig

You can see that the network statistics are displayed using the “ifconfig” command.

Conclusion

This post contains a short yet profound and step-by-step guide on installing net-tools to run the “ifconfig” command. This post also provides an alternate “ip a” command to get the network stats without even installing the net-tools. Keep on learning with linuxhint.com.

]]>
How to Break from a Bash While Loop? https://linuxhint.com/break-from-a-bash-while-loop/ Mon, 22 Feb 2021 11:49:33 +0000 https://linuxhint.com/?p=90716

Loops are an extremely useful means of performing repetitive tasks not only in Bash scripting but also in all other programming languages. It enables us to write a task (that is supposed to occur multiple times) at once and enclose it within any desired loop so that the said task can be performed repeatedly. Different loops are used in every programming language, i.e., multiple types of loops can be used with every programming language. Amongst all types, the most frequently used loops are the “for” loop and the “while” loop.

A major difference between the execution of the “for” loop and the “while” loop is that in the former one, the incrementing or decrementing variable is specified with the loop whereas, in the latter, that variable is specified after the task that is supposed to be performed repeatedly is stated. The “while” loops appear to be more convenient for the programmers syntactically.

The concept of infinite loops in every programming language is also very common, i.e., a loop that never terminates and its condition assesses to be always “true”. At times, these loops are written accidentally by the programmers, however, there are situations in which such loops are written deliberately. Either way, there can be certain conditions in which we want that infinite loop to break.

Apart from the scenario that we have discussed above, there are times that we purposely create finite loops that we want to run based on a specific condition, wherein we want the normal flow of that loop to break. For both scenarios, there should be a proper mechanism in which we can break a loop whenever a certain specified condition is met.

We can achieve this objective using the “break” statement with our loops regardless of whether they are finite or infinite. Since the “while” loop is one of the most commonly used loops in any programming language, therefore, we will see how we can break from the a “while” loop in Bash in Linux Mint 20 by sharing an example of Bash script with you.

Example Script for Breaking from a Bash While Loop in Linux Mint 20

For demonstrating the usage of the “break” command in Bash, you have to create a Bash file in your Home directory. In our case, we have entitled it as “BreakWhile.sh”. You can also have any other name for this Bash file. Once this file is created, you have to open it up with any text editor and then write down the script shown in the following image:

In this script, we have defined a variable named “number” and initialized it with the value “1”. Then we have a “while” loop whose iterating condition is that the value of the variable “number” should be less than 10, i.e., this loop will keep iterating until the value of the “number” variable is less than 10. Then in the do-done block, we have an “if” statement whose condition is that whenever the value of the “number” variable will be equal to “9”, our “while” loop will break. Otherwise, it will keep running. Then we have simply printed the value of the “number” variable for each iteration of our “while” loop. Finally, we have incremented the value of our “number” variable, i.e., the value of our “number” variable will exceed one after every iteration of our “while” loop. The above script will result in a situation in which the number “9” will never be printed since when the value of our “number” variable will be incremented to “9” our “while” loop will simply terminate without printing anything on the terminal.

To verify this situation, we have to execute the Bash script that we have just created using the command shown below. However, before executing this command, you should ensure that you have saved your Bash script file.

$ bash BreakWhile.sh

The output of this script is shown in the following image. You can easily see that the numbers printed on the terminal are from 1 to 8 and the number “9” is not printed which means that our “while” loop has terminated successfully by using the “break” command.

Conclusion

This article demonstrated a quite simple example of breaking from a “while” loop in Bash in Linux Mint 20. The very same Bash script can be executed in any other Linux distribution of your choice, and it will render the very same results. Also, you can even use this “break” statement with the “for” loop or any other loop in Bash to break its normal flow. This statement is extremely useful especially if you have a certain special case within your program for which you do not want your program to continue its normal execution or you may even want the control of your program to take an altogether different path of execution.

However, an important thing to consider over here is that we only intended to give you a head start with using the “break” statement with the “while” loop in Bash in Linux Mint 20. That is why we have just created a simple Bash script for printing some sample numbers on the terminal, which are less than 10 except for the number “9”. But it does not mean that the break statement is only used with such simple scenarios. You can create even more complex programs to test the effectiveness of the “break” statement with the “while” loop in Bash in Linux Mint 20. Hopefully by going through this tutorial, you can easily create any bash script of your choice using the break statement.

]]>
How do I Prompt for Input in Bash? https://linuxhint.com/prompt-for-input-bash/ Mon, 22 Feb 2021 09:53:15 +0000 https://linuxhint.com/?p=90250

It is often necessary to perform calculations depending on user inputs when creating a Bash script. Throughout this guide, before carrying out a basic operation with a shell script, first, let’s take a glance at interpreting and verifying user inputs. We will be using the integrated Bash read command to interpret the Bash user input. The read command takes some value as input via the user and allocates it to the variable. It read out only a solitary line through the Bash command terminal. In this guide, you would learn how to interpret the user input from the terminal and the script.

To implement the read command, here is the syntax:

read <variable name>

Example 01:

Let’s take a simple example of reading input from the user in bash when prompt. Open a terminal and create a new file “input.sh”.

Open the file and add a little code to it as below. Firstly, the echo statement is asking the user to add input value. The read statement is used to input user value, which will be saved to the variable “NAME”. The last echo statement is used to print the answer with inputted value as “$NAME” variable.

Execute the file using the bash command. Firstly it will prompt for the name. When the user inputs the value “Aqsa”, it will print the message with the value within it.

Example 02:

Open the old file and write the below code into it. We may be using the integrated read command; to a user with a query, using that -p option. You have to summon up to use the “readline” keyword -e to let line editing with arrow keys. After that, use the variable to print the path of a file entered by a user at the command shell.

Let’s check the output of this code using the bash command in the terminal. You will see it will ask for the file path to be entered in the shell. When you enter the required value and press Enter, it will print it out.

$ bash input.sh

If you want to suggest an answer, you have to use the keyword “–i” after the string with the path in inverted commas.

Let’s check the output for updated code using the bash command. You will perceive that it will suggest you a file path as below.

Example 03:

Let’s have another example of prompting for input in a shell. Write down the below code in the file “input.sh”. We have two read commands to add login credentials by a user on the shell. The keyword “-sp” is used to hide the credential “Password” while entering the shell.

On execution, you can see that the user has entered its credentials while the password is hidden while entering. In the end, it has displayed the message to pay thanks to the user.

Example 04:

We have another example to read multiple car names as values from the user’s bash shell. For this purpose, we required three variables as “car1”, “car2”, and “car3”. We have an echo comment that is asking for the names of cars. Read command is used to read inputted values (names of cars) by a user in a shell. The next three echo statements will print the messages with the names of the car consecutively.

Using the bash command, execute the file. It will ask for the names of cars you like. When the user entered the names of cars consecutively, it will save them into variables of a read command and print them out by using the next three echo statements one by one.

Example 05:

In the above example, we have seen how to prompt user input while saving the input into three variables. In this example, we will learn about how to read user inputted values in one variable as array members using the keyword “-a”. So, open the same file and write the below code in it. The echo statement will ask you to enter the input required. The read statement has the keyword “-a” to take multiple values from the user and save them to the one variable array “NAMES”. At the last echo statement, all the inputted values are printed as array members within the string text.

While running the file “input.sh”, the user has been prompted to enter the values. When the user enters the values, these values have been saved into the array variable “NAMES”. After saving these values, the echo statement will be executed and print out the inputted names as array values within itself as shown.

Example 06:

Let’s take the same file with little change in the script. We have written two read commands to take value from a user as input in a shell and saved them in two variables, “NUM1” and “NUM2”. After that, both the variables have been printed out.

In the command terminal, write the Chmod command to assign execution privileges to this file.

$ chmod +x input.sh

When you execute this file using bash, you will see it will prompt you to add numbers consecutively. When you enter the required values, it will print out both numbers separately.

If you want to validate that any field or variable is left blank by the user, you can update the previous code as below. The keyword “-z” is used to check both variables, if they have any blank spaces in them.

While the execution, the user has added space as a number. The user got a message to try again because the variable entered by the user got spaces.

Let’s try the same code with some conditions over the numbers inputted by the user. If the user input’s any character other than those mentioned in the below code, it will pass a message.

While trying this code, a user has added one special character, which generates a prompt message.

Conclusion

In this guide, you have successfully learned how to prompt user input in the shell and interpret the user input using some very simple examples.

]]>
How to Write Bash If/Else Statements in One Line https://linuxhint.com/write-bash-if-else-statements-one-line/ Sun, 21 Feb 2021 19:34:03 +0000 https://linuxhint.com/?p=90692 Bash is a flexible programming language that allows you to write programs just the way you like. Before getting into the article, we would first like to share with you a good programming practice. Whenever you write a program in any programming language, the readability of the code should always be your priority. This is because your code is not only used by yourself but there will be many other programmers who will be using and reading your code. Therefore, your code should be readable enough to be understood by everyone.

Today’s article introduces you to the concept of one-line programming. Bash allows you to write components, such as loops or conditional statements, in one line. You might wonder why we should consider writing these components in one line when we have just explained to you the concept of readability. To understand this, consider the following scenario: you have a program spanning a thousand lines. Such a lengthy code would be difficult to visualize, as well as to debug. In this situation, if your code contains many different loops and conditional statements, then it would improve the readability of the code to write several statements in one line to make your code look more compact.

The following tutorial shows you how to write Bash if/else statements in one line in Linux Mint 20 by providing several examples of these statements.

Methods for Writing Bash If/Else Statements in One Line

To learn more about writing Bash if/else statements in one line in Linux Mint 20, examine the following example Bash scripts:

Example 1: Comparing Two Strings in One Line

In the first example, we will write a Bash script that will compare two strings in one line. To achieve this functionality, write the Bash script shown in the image below in a Bash file:

We will compare two pre-defined strings in the “if” part of the statement, and a message will be displayed if this part is executed. Then, the “else” part of the statement will also display a message if it is executed.

To run this Bash script, we will use the following command:

$ bash OneLiner.sh

Since both strings were equal, the “if” statement will be executed. We will obtain the message shown below upon execution of this script:

Now, we will tweak our Bash script a bit by changing one of the strings, as shown in the following image:

After making this change, when we execute our Bash script again, the “else” statement will be executed, and we will get the message shown in the image below:

Example 2: Comparing a Variable with an Integer in One Line

Now, we will write a Bash script that will compare a variable with an integer in one line. To achieve this functionality, write the Bash script shown in the image below in a Bash file:

We will create a variable named “var” and assign it the value “20.” Then, we will compare the value of this variable with an integer “25” for equality in the “if” part of the statement. A message will be displayed if this part is executed. Then, the “else” part of the statement will also display a message if it is executed.

Since the value of the variable “var” was not equal to “25,” the “else” statement will be executed. We will obtain the message shown below upon execution of this script:

Now, we will tweak our Bash script a bit by changing the value of our variable “var” and setting it to “25,” as shown in the following image:

After making this change, when we execute our Bash script again, the “if” statement will be executed. We will obtain the following message upon execution of this script:

Example 3: Comparing Two Variables in One Line

Finally, we will write a Bash script that will compare two integer variables in one line. To achieve this functionality, write the Bash script shown in the image below in a Bash file:

We have created the two variables “var1” and “var2” and assigned them the values “25” and “20,” respectively. Then, the values of these variables will be compared for equality in the “if” part of the statement, and a message will be displayed if this part is executed. Then, the “else” part of the statement will also display a message if it is executed.

Since the value of “var1” was not equal to the value of “var2,” the “else” statement will be executed. We will obtain the following message upon execution of this script:

Now, we will tweak our Bash script a bit by changing the value of our “var2” to “25” so that the values of both the variables become equal, as shown in the following image:

After making this change, when we execute our Bash script again, the “if” statement will be executed. We will obtain the following message upon execution of this script:

Conclusion

This article provided three different examples and their slight variations for writing if/else statement in Bash in Linux. This tutorial showed you how to use conditional statements in Bash all contained within a single line, making your code look more compact and readable.

]]>
How to Obtain a Bash Substring After a Specified Character https://linuxhint.com/bash-substring-after-character/ Sun, 21 Feb 2021 13:12:03 +0000 https://linuxhint.com/?p=90621 In programming, a string is a series of characters, whether as a precise constant or some sort of variable. The characters contained within a string can be any number, digit, or special character. Keywords can be used to obtain a substring after certain characters, and all keywords work the same. Some examples of keywords include the following:

  • Cut
  • Awk
  • Sed

This article provides several examples to improve your understanding of the concept of obtaining a substring after a certain character.

To follow the examples provided in this tutorial, first, log into your Linux system and open the terminal. Next, create a new file with the name “input.sh.”

Example 1: Using the Cut Keyword

Open the file “input.sh” from the home directory, and write the following code in the file. In our first example, we will define a string named “string” with some value in it having some characters and numbers. We will use the keyword “cut” in this code, followed by “-d,” to obtain the substring of the particular string. After that, we will provide the exact character in inverted commas as “-“ so that the substring will be searched after this special character.

Here, it is important to understand the main idea of substring formation. You must remember how to include the keyword “f” when using the “cut” command. The keyword “f” can be used in various ways to create a substring, so let us look at this particular method.

-f2: text after the first special character “-“ and before the next “-“

This means that it should display the substring “bar” because it is located after the first “-“ character and before the next “-“ character.

After running this bash file, we obtained the substring “bar,” as we expected.

Now, we will check the same example for the “-f2-“ keyword. Update the file, as below.

-f2-: the text following the first special character “-“ regardless of whether there are numerous “-“ characters.

This implies that it will display the substring “bar-123” because it is located after the first “-“ character, regardless of whether any “-“ characters exist.

After executing this bash file, we obtained the substring “bar-123,” as it is located after the first “-“ character.

We will now take the same condition, with little changes to the string and characters. We have defined the new string “str” and assigned it a different value. In this example, “i” is the special character to be searched from the original string, and from this character onward, we will create a substring. In this case, we have used:

-f2: to create a substring following the first special character “i” and before the next character “i.”

This implies that it should display the substring “ltEff=str” because it is located after the first “i“ character.

When the file runs, a substring will be obtained before the next “i” and after the first “i.”

You can try this method with the same line of string, as shown in the image below:

It will display the same result as above.

Now, we will use the “cut” keyword with little change to the “f” condition in a single line. We will use “f1” in this case to change the outcome of the substring. We are using:

-f1: to create a substring before the first special character “i.”

This infers that it should display the substring “GenF” because it is located before the special character “i.”

The output below is as expected.

Here, we are using the same example with little change. We have been using the old method for it.

The result of this script is the same as above.

Next, taking the same previous example, we use the “cut” keyword, while changing the keyword “f.” Here, we will use “f3” to change the outcome of the substring, and we are using:

-f3: to create a substring after the next special character “i.”

This indicates that it should show the substring “ng.-01234” because it is located after the next special character “i.”

We will run the same code using the Bash command. You can see the new result below:

Example 2: Using the Awk Keyword

Open the file “input.sh” and write the appended code in the file. Here, we have declared an echo statement with the string “foo-bar-123” using the “awk” keyword. The print term is followed by the “-F-“ keyword. This will create a substring after the next special character, which is “123,” and print it. There is no need to define the special character in this case.

The following is the output “123” that was mentioned above.

Example 3: Using the Sed Keyword

In this example, we will update the same file with the code provided below. In this case, the keyword “sed” is used instead of “cut” or “awk.”

This code will display a similar output to that of the previous example.

Example 4: Using Special Characters

In the next example, we will update the same file with the code provided below. Here, we will define three strings: “string,” “searchstr,” and “temp.” We have “${string%$searchstr*}” in the code. The “%” will search for the value of the variable “searchstr,” which is “and,” and will remove everything after this special variable from the original string. The remaining text will be saved in the variable “temp.” Now, the variable “temp” will be printed, along with the text “This is a new string.”

If we execute the above code, the original string will be printed first; then, the new substring will be printed.

Taking the same example with a small update, we will use the “#*” string so that everything following the value of “searchstr,” which is “and,” will be inserted into variable “temp.”

When you check it in Bash, you will see that the old string will print first. After that, since “it will be removed” is a new value of variable “temp,” that is why it will be printed at the next line first, along with the text “This is a new string.”

Conclusion

If you want to obtain a substring from any string using some special character in it, you can do so by utilizing the methods provided above.

]]>
How to Create a Bash Function that Returns an Array https://linuxhint.com/create-bash-function-return-array/ Sun, 21 Feb 2021 12:49:46 +0000 https://linuxhint.com/?p=90599 It may appear at first glimpse that returning an array from a Bash function is not realistic. Considering all the benefits, it can be useful to call multiple methods to construct arrays to split up the process of gathering all the appropriate parameters for a YAD call.

There are many reasons why one might want to restore a BASH array:

  • Managing the lifespan of arrays is simpler because they are assigned locally.
  • For just-in-time attainment, obtaining arrays from methods may help.
  • To support log algorithm techniques, the names of methods that return arrays may be cast off.

You may believe that Bash loses the capability to return function arrays. However, that is not exactly correct. It is possible to move the resultant array to a method by reference, taking cues from C/C++ developers. Such a strategy allows the method to continue to be free from references towards a global variable. The following article shows clear instances of this case.

Example 1: Returning an Array

Log into your Linux system and open the command terminal to proceed. We will create a Bash file named “script.sh” using the touch command to return the array using the Bash function. The script is as follows:

$ touch script.sh

You can view the newly created file in the Home directory. Open this file and write down the appended code into it as-is. Here, we are attempting to create an associative array through an argument in a method from either a list pass.

Initially, we have created the function foo().

Inside this program, we have removed the “declare” term, which is a Bash pre-configured command that allows us to change or customize the attributes, the methods of the shell smeared to the variables, and demonstrate the values of these attributes inside the span of our shell command terminal. Moreover, it can be used to define a lengthy variable. Lastly, it is used to define the variables.

We have added the “fooval” value to the “arr” array.

The keyword “–A “is used to create the NAMEs associative array if supported. We must use the list/array as a global variable, which implies that only a method, not a script, can perform this action.

We have also created another array, named “myarr,” for use as a reference. Bash allows the name of a relative variable arr to be dissimilar to the name of the relative variable myarr.

After that, in the eighth line, we have passed the “myarr” array to the Bash foo() function as a reference.

In the past, we used the “for” loop to print both the “arr” and “myarr” arrays to the foo() function.

We will now check the result of this code. Execute the Bash command to run the above code. You can see that the array has been returned to the function and then printed.

$ bash script.sh

Example 2: Returning another Array

Let us look at another example of returning arrays to a function. Open your command terminal and create a new file named “openvpn.log” using the touch command, as follows:

$ touch openvpn.log

Now, open the “openvpn.log” file, and write the following text into this file, as shown. Save this file and close it.

Again, open the command shell and create another file named “script.sh,” using the touch command to add the Bash script to the file.

$ touch script.sh

Next, open the “script.sh” file and append the following code into this file as-is. Save and close this file. This script will use a method that reads values/strings from a document and returns an array:

  • Declaring the array: clients
  • Allocate the returned array of the method to array clients
  • Show array: clients

Let us now have a detailed look at the working of this script.

  • We have declared a global array of “clients” using the “declare” keyword, followed by “-A.”
  • The readArray() function has been defined. In this function, we have declared some local variables. The local variable “array” is empty, but “i” and “j” have been defined with the 0 value to be used as iterators.
  • Using the read mode, we will read the text from the file using iterators to increment the indexes.
  • The line “clients[$((i++))]+=${LINE};” is used to append the text lines to the globally defined “clients” array variable.
  • After that, “j++” is jumping on the next index.
  • The variable “$1” is used to save and return the array that was just created from the “openvpn.log” text file.
  • On the outside of the function, the string has been declared as “$string” and has been given a file path as a value.
  • This string has been passed to the readArray function as a reference to read text from this file.
  • After that, the “clients” array has been printed, and the entire text within it has been displayed in one line.
  • Now, we will display a message that the array is no longer empty.
  • The “for” loop has been used to convert the contents of the “clients” array into the array type and declare an index for the contents using the statement “echo “$i: ${clients[$i]}.”
  • Finally, we displayed a message and printed some converted array values separately as a single indexed position of an array.

Let us now check the output of this Bash script. Run the Bash command to execute the “script.sh” file. As you can see, the first echo statement will print all the text from the “openvpn.log” file, which has been saved in the “clients” array as one line. The second echo statement will display the string message. The third echo statement will display the “clients” array in indexed form, as it has just been converted. The fourth one will display a message again. The final one will display the contents of the “clients” array individually.

Conclusion

This article showed you how to return arrays (especially associative arrays) to a function using the “declare” built-in command with two examples. I hope that this article helped you to better understand this topic.

]]>
Create Bash Functions with Arguments https://linuxhint.com/create-bash-functions-arguments/ Sun, 21 Feb 2021 12:46:17 +0000 https://linuxhint.com/?p=90600 In programming, a function is an entity that performs an activity when it is called. This function may or may not accept arguments, which are the parameters that determine the activity that a function performs. Many of those who are new to programming might wonder why we even need to create functions when we can simply write a program as-is without breaking it into different parts.

This is where the concepts of Modularity and Code Reusability come into play. Modularity, or modular programming, is a highly recommended programming approach that breaks code into chunks to enhance readability, which also results in Code Reusability. Code Reusability refers to the ability to reuse a certain piece of code repeatedly, thus avoiding the task of rewriting the code every time it is used.

Modularity and Code Reusability are why functions are so extensively used in all programming languages, regardless of whether they are high-level or low-level. However, it can be quite tricky to create functions that work with the correct arguments or that accept certain arguments. This article uses several examples to show you how to create Bash functions with arguments in Linux Mint 20.

Examples of Creating Bash Functions with Arguments in Linux Mint 20

Functions with arguments in Bash can be created very conveniently. The following examples demonstrate how to create various Bash functions with arguments.

Example 1: Passing a String Argument to a Function

In this example, we will write a Bash script that will define a function to take a string as an argument. This can be done by copying the script shown in the image below in a Bash file. You can name your Bash filename according to your preferences:

In this Bash script, we created a function named “Hello.” Inside the body of the function, we will print a message, followed by “$1,” which represents the value of the string argument that will be passed to this function. Then, outside the body of this function, we called this function with its name while specifying the string argument to be passed to the function inside of double-quotes.

After creating this Bash script, we will execute the script with the following command:

$ bash Function.sh

The output of this script is shown in the image below:

Example 2: Passing More than One String Argument to a Function

In the next example, we will write a Bash script that will define a function to take two string arguments. This can be done by copying the script shown in the image below in a Bash file:

The script used in this example is roughly the same as the one that we wrote in our first example. The only variation is that, in this script, we used two placeholders (i.e., “$1” and “$2”) for our arguments, since we are passing two string arguments to this function. Then, in the same manner, we called this function with its name, followed by two string arguments enclosed in double-quotes.

After executing this modified script, you will obtain the following result:

Example 3: Passing Integer Arguments to a Function for Addition

To add two integers in Bash, we will write a Bash script that will define a function to take two integer arguments. This can be done by copying the script shown in the image below in a Bash file:

In this Bash script, we defined a function named “Sum.” Inside the body of this function, we created an expression to add the values of the integer arguments “$1” and “$2” and store the result of the sum in the variable “add.”

We will display the result of this calculation using the “echo” command. Outside the body of this function, we called it with its name, followed by the two integer parameters, “22” and “27.”

When we execute this Bash script, we will obtain a message in our terminal, followed by the result of our addition, which will be “49.” The output of this script is shown in the following image:

Example 4: Passing Integer Arguments to a Function for Multiplication

To multiply two integers in Bash, we will write a Bash script that will define a function to take two integer arguments. This can be done by copying the script shown in the image below in a Bash file:

In this Bash script, we defined a function named “Product.” Inside the body of this function, we created an expression to multiply the values of the integer arguments “$1” and “$2” and store the product in the variable “mul.”

Then, we will display the result of this calculation with the “echo” command. Outside the body of this function, we called it with its name, followed by two integer parameters “2” and “3.”

When we execute this Bash script, we will obtain a message in our terminal, followed by the result of our multiplication, which will be “6.” This output is shown in the following image:

Conclusion

This tutorial showed you four different examples of creating Bash functions with arguments. These examples were based on the functions that display messages, as well as those that perform some basic calculations. With these examples, you should now have a basic idea of passing arguments to functions in Bash in Linux Mint 20. However, the complexity of these functions can vary according to the requirements of your program.

]]>
Bash script to While Loop while Reading Stdin https://linuxhint.com/while-loop-bash-script-reading-stdin/ Sun, 21 Feb 2021 12:11:00 +0000 https://linuxhint.com/?p=90468 The concept “stream” in a computer applies to something that might move data. Any instruction you are executing in the terminal would be at any position of the flow. These positions can be an origin or an outflow. Let’s get a quick overview of the specific Stdin stream. In Linux, stdin refers to the default or standard input. The input it requires must be a text. To acquire data or information from you, it’s the file handler that your procedure readout. Almost all flows are viewed in Linux as if they are directories. We may read/write information from all of these streams, exactly as you can read/write a document. By using a special file descriptor number related to it provides a great approach to access a document. There have been special values allocated to every one of these throughout the situation of such streams. Stdin has a value of 1.

Stdin: 1

Let’s begin by understanding through practice about Stdin Stream using while loops. At very first, we will be having a basic example of the stdin as read. Execute the instruction below. The instruction would demand keyboard input. In this, through stdin, the reading tool gets the text.

$ read

Example 01:

Create a new file, “input.sh” and add the appended script to it. We have been using the while loop to read the text by a user from the terminal and print it. The script is named with a “/dev/stdin” as the very first $1 parameter, in which the corresponding approach reads the regular input from the console. Save this file and close it.

Open the terminal, and run the newly updated file “input.sh” as:

$ bash input.sh

When you execute the file using the bash command, you will be jumped to the next line to write something. As you can see below, the user has written a one-line text and press Enter.

The text written by a user will be read out first and printed out on the next line as below.

You can even provide one space between your text input as below.

Example 02:

Now we will read the text from the file. Update the same file “input.sh” by providing the filename “script.sh” as the very first $1 parameter. The corresponding approach reads from this document.

We have the following text information in the file “script.sh” as below. Let’s check how it works.

Execute the file “input.sh” using the bash command. You will see that the read stream reads out from the provided file “script.sh” and print it out in the terminal as below.

$ bash input.sh

Example 03:

Let’s have an example to read each directory one by one using stdin. You have to consider the parameter -u with the read. In this, “-u 1” implies “read from stdin.” In this code, “line” represents the filename, and the increment “i++” is used to jump over to the next directory or file. It will also count the file number that has been read as well. Let’s run this code to check what happens next.

Execute the bash file “input.sh”. It will prompt you to enter some text to jump over to the next file. Here “comm” represents the name of the first file.

$ bash input.sh

While continuing this, you can see we have a list of files that we have gone through.

Example 04:

In this example, we have two related files to read from. Assign the required privileges to both files using the “Chmod” command as below.

chmod u+x filename

Write the below code in the file “input.sh”. Until the “while” loop is getting lines, it will print those lines. While the “line” refers to another file “script.sh”.

We have the below code in the file “script.sh”. While the loop is running, it is printing the line number.

Execute both files using “”./” at the start of the filename and separating using “”|” in the shell. You will see that it is printing the line numbers while printing the text from the files as well. It’s a very simple method to correlate two files or their contents.

$ ./script.sh | ./input.sh

Example 05:

Let’s end this topic by having this simple and efficient example. We have a file “script.sh” with the below contents or names of persons. We will be reading these names one by one from another file.

Update the file “input.sh: with the below script. In this script, we have a while loop to elaborate “stdin” working. We have been using read “read –r” while reading from another file as other than standard input. On the other hand, using “-u” as bash-specific, the standard output from the user in the terminal. Here, the “name” is the text or content of the file “script.sh”. The option “-p” is used to “read”. The read statement will read the “name” from another file and ask if you want to delete it or not. The keyword “ip” is used for user response to affirm the action of deletion. Whatever the user response is, it will print it out. In the “if” statement, it will check if the standard input from the user is same as “y”, then it will print out some message as mentioning that it has been deleting the “name”. This process will be reiterated until the last content of the file “script.sh”.

Let’s have a look at the output of the above code. Execute the file using the bash command. The system will ask you if you want to delete this “name” or not. Enter “y” and tap “Enter”.

$ bash input.sh

Here on pressing “y”, it will print “y” and show a message that it has been deleting the particular “name”. After that, it will switch to another “name”.

It will ask you to delete the names until all the names or contents of file “script.sh” have been lopped over as below.

Conclusion:

We have magnificently gone through all the simple examples of standard input while using the “while” loop in the bash script.

]]>
How do I Create an Alias in Bash? https://linuxhint.com/create-bash-alias/ Sat, 20 Feb 2021 22:07:56 +0000 https://linuxhint.com/?p=90339 Bash alias is a command-based shortcut title. Every alias comprises a single word (or maybe even a single letter), which can be used rather than a relatively long command. In the Linux system, there have been several instructions that we’ll need to utilize daily. If we can run some popular instructions by typing quick instructions, it would be very beneficial for all of us. Via bash aliases, Linux users can conveniently build commonly used shortcut commands for big commands. Bash aliases are not just used to ease the job and thus save users’ time.

Create Alias in Bash:

Most people prefer to execute commands using shortcuts. You could find yourself, for instance, using the “ls –F” instruction many times. You could even create a detour for this instruction conveniently: for example, “lf”. So when you have to use “lf” in which the shell expects a command, the shell will replace “ls –F”. The alias definition begins with the word “alias”, preceded by a title of the alias, the equivalent symbol, as well as the instruction we intend to execute as we enter the alias. It is appropriate to encapsulate the instruction in quotations and without any spacing all over the equal sign. There is a need to announce each alias on even a new line. It is really easy to construct aliases within Bash. The following is the alias syntax:

$ alias=alias_name=”command_to_run”

Alias Types:

A user may temporarily or permanently claim an alias. It is possible to be using temporary aliases as soon as the user’s access persists. Hence there are two types of alias, temporary and permanent. We’re going to have a look at and analyze both types. Firstly, login from your Linux system and open your command terminal. You will be able to see the already defined default aliases of your Linux system using the simple “alias” command in the terminal, and the list will be displayed as shown below.

$ alias

All of these mentioned techniques are carried out on Ubuntu. Conversely, so far, since you’re dealing with Bash, they can function on every Linux distribution.

Temporary Aliases:

So far, because the console session is operating, such a kind of alias persists. It would lose the alias once the shell is ended. Let’s have a look at the temporary alias. Open your command terminal and navigate to the Desktop directory using the below command:

$ cd ~/Desktop

Perhaps one of the utmost popular instructions on the Linux terminal is the “ls” instruction. Typically, with either the “-la” option, we use this command to display all files and folders, plus secret ones, as in the large list layout.

Now using the “ls” command, we will create the alias.

$ alias L=" ls –la"

The performance of the “L” & “ls -la” instructions may be the same upon constructing aliases.

$ L

If the window is closed and the consumer begins a new session again, the alias instruction would not operate.

$ L

Permanent Aliases:

Bash may recall the formation of both the alias as well as its purpose when it is formed. You have to announce it in the .bashrc document to create permanent aliases. The document .bashrc has a bash script that is run each moment a bash process begins. The position is “~/.bashrc”. For every single person in the process, it is special. Let’s have an example of permanent aliases. You can update your system without using the aliases using the update and upgrade command as below.

$ sudo apt update && sudo apt upgrade -y

For making your preferred aliases, .bashrc is indeed a popular approach. Within your setup, .bashrc might not have been active. Create and launch the .bashrc using the nano command. If it is not available, an empty document would be opened.

$ nano ~/.bashrc

File .bashrc will be opened. Add the below line to the file to make aliases for an update of the system.

alias update=" sudo apt update && sudo apt upgrade –y"

Save the file and close it. After that, run the source instruction in the terminal to replenish the file.

$ source ~/.bashrc

This is the moment to verify whether the alias is working or not. Restart the Linux system, get yourself logged in to your Linux system, and execute the alias “update” command that we have just formed. You can see that the alias has been successfully working as it should be and updating the system.

Remove Bash Alias:

To remove the formerly formed command aliases, the term unalias is being used. That alias would not function while using this instruction. Well, you may use the unalias instruction to completely disable it if you find that you no longer want to have the shortcut command. Firstly check the already formed aliases in your system using the alias command.

$ alias

You can see a newly formed alias command “update” is listed in the list below.

Now execute the “unalias” command to delete the previously made shortcut command.

$ unalias update

While checking again in the list of aliases, you can see that the “update” alias has been removed completely.

You can also erase the aliases from the .bashrc file by opening it using the nano command and deleting it from the file. You can simply comment on the alias line or just remove it completely. After that, run the source command to reflect the changes. Save the updated file and restart your system to check the changes. When you again try the “update” alias command, it will not work.

Conclusion:

In this guide, we have studied alias and their two different types. This article is a simple illustration of how to generate an alias as well as execute the commands that are quite often used without typing each instruction over and over yet again. One could now ruminate more about instructions to use far more and generate shortcuts in one’s command shell for them.

]]>
How to Simulate an Array of Arrays in Bash https://linuxhint.com/simulate-bash-array-of-arrays/ Sat, 20 Feb 2021 19:13:42 +0000 https://linuxhint.com/?p=90321 Bash is indeed an interpreted, interactive language, and how much space to reserve in advance does not have to be known. It is also possible to make ready a new array dynamically without declaring it or extending a previously defined array to include further entries. Still, multidimensional arrays aren’t supported by bash, and we can’t get array components that are also arrays. Fortunately, multidimensional arrays can be simulated. This article will provide some illustrations of the simulation of an array of arrays in a bash script.

Example 01: Using Simple “For” Loops

We have an example of simulating an array of arrays using the simple method. Let’s start demonstrating how to load a user-defined m x n table with random numbers (that aren’t random, because each column will at all times have a similar number in each run on most of its rows, but that does not apply to the question), and print it. When we work on either a bash that you do have, bash version 4, the below script would certainly work efficiently. We should not solitary declare 0; that is more like a perfect solution to values being accepted vigorously. We have declared an array with the “-A” keyword.  If we don’t define the associative array using -A, the code may not work for us. The read keyword is then used to read the user’s input, which is rows and columns of a table. Then we have used two “for” loops for the incrementation of rows and columns of a table. In for loop, we have been making a two-dimensional array. In the next for loop, all the values of an array have been displayed.

When you run the bash file, it will ask a user to enter rows and columns as “m” and “n”. After that, for loops will generate a two-dimensional table as below.

Example 02: Using Hashes

Taking the same instance, we can emulate the arrays using hashes. However, we have to be more careful about leading zeros and several other stuff. The next explanation is working. However, the way out is very far from ideal. We have been taking rows and columns manually. For loop is used to make a matrix. Then we have been using hashes to emulate the two-dimensional array. At last, the array will be printed out as below.

Execute the file “input.sh” in the bash shell using the bash command. You will find a table with rows and columns number mentioned.

Example 03: Using Associative Arrays

Let’s have an example of simulation having a somewhat similar effect using the associative arrays used as an array of arrays as below. After the declaration of the associative array, we have defined values for arrays separately. After that, we have made it to print out the values in two dimensional way.

You can see the output as a two-dimensional array while running the file. If we ignore the “declare -A arr” line, the echo statement may display (2 3) rather than (0 1), since (0,0), (1,0), and others may have been used as a mathematical expression and calculated to 0 (the value at the right side of a comma).

Example 04: Using Name-references

In bash, it is a frequent issue with referencing arrays inside arrays that you’ll have to construct name-references using declare -n. That name afterward -n serves as a name ref for the value allocated (after =). Currently, we handle this variable only with attribute name ref to extend as though it was an array and extend the appropriately cited array as beforehand. Let’s have an example of name refs. We have successfully declared two arrays. After that, we have assigned both the arrays to another array as a member. We have used for loop to make a two-dimensional array. We have made another variable to add the one-by-one values of the array “group” into it for comparison. Deep down, it will go to members of inner arrays “bar” and “foo” to take values and compare them while printing the message.

When we execute the file “input.sh”, you will see the below output. The variable “lst” has values of inner arrays within the array “groups”.

Example 05:  Using Cut Keyword

Only now, I’ve stumbled into it. There had been a fairly straightforward approach that worked for everyone. To show a main map for the system, I decided to use an array containing a device name and a screen location. We have to concatenate the title of the unit and the corresponding location of a display into some single string, using only a delimiter, which we assumed will not occur in either of our values (in my case, I used .). And I used a “cut” keyword to split the concrete values into their components if necessary. There may be a clearer and easier approach to do it, though, and this is only to illustrate that in a sense, in bash, we can build a multidimensional array, although it does not help it. After that, you have to print both the device name and its location separately after creating the substring.

Let’s run the bash “input.sh” file. You will see the separated device and its location in the shell prompt as while execution. The solution works using the cut command.

Example 06

Let’s take a little longer example to emulate a multidimensional array. In the load_alpha() function, all the alphabets will be loaded into the array. After that, the print_Alpha() function is declared and used to print out all the alphabets in the row-major order as a matrix or two-dimensional format. On the other hand, we have been using the rotate() function to rotate the array. Let’s try this example in the bash shell to see results.

While execution, we have found a very beautiful structure of multidimensional array in the bash shell as below

Conclusion

We have successfully tried some examples for simulating arrays of arrays in bash. I hope it works!

]]>
Remove a Specific Element from an Array in Bash https://linuxhint.com/remove-specific-array-element-bash/ Sat, 20 Feb 2021 18:17:33 +0000 https://linuxhint.com/?p=90309 Although the entire process is not very simple and might seem like a hack, you could perhaps remove an element from the existing array. We could be using more than one method to remove an element. One of the methods is “unset,” which is used to delete an element from a specific index and afterward replace it with some other array. Several other sets of elements can be deleted using: also. You can remove the list element from the end but only the solitary one using the pop() method. Let’s have some examples for this.

Example 01: Remove Element using Prefixes Matching

Our first method; to remove a specific element from an array is prefixes matching. Login-in from any distribution of Linux you have been currently using and open the terminal in it.  Create a file “input.sh”. Open this file from your home directory and write the below code in it.

Let’s explain this code step by step. To delete a specific element, you have first to create an array. So, let’s create an array named “array” and assign it some values, as I have assigned it three values; aqsa, raza, and saeed.

array=(aqsa raza saeed)

Now we have created another variable, “delete,” and assign it a value similar to the one which is residing in the “array”. In reality, this technique is used to eliminate the prefixes’ elements resembling $delete, not essentially entire elements.

delete=saeed

After that, we have been using the echo statement to print the elements of an array other than that of the same prefixes. Here is the code to do so:

echo ${array[@]/$delete}

When you have been working with strings, then you have to use the same script with a few changes as below:

array=(${array[@]/$delete})

You will see the output below. It will display all the elements of the array skipping the value similar to prefixes variable “$delete”.

If somebody wants to remove more than one specific element from the array, they can easily do it easily. Just write the below code in the file. Let’s explain this code.

Assign the similar values from the array to the new variable as I have assigned two values to variable $delete.

delete=(aqsa raza)

Now we will use the “for” loop to match the prefixed values to the array with the variable $delete. The “for” loop will match the values to $delete and make another array that wouldn’t have similar values.

for del in ${delete[@]}
do
array=(${array[@]/$del})
done
echo ${array[@]/$delete}

On execution, it will display the remaining value, which is “saeed”.

Example 02: Remove Element Using Unset Command

The other method is “unset,” being used to remove an element from a specific index and duplicate it to a certain new array. Throughout this scenario, it is not obligated just to unset. Since unset doesn’t delete an element, it simply assigns the null string within an array to a specific index. Write the below code in your file.

Here we have defined a global array with the keyword “declare” followed by “-a”. We have assigned some string values to it and print out all the values of an array.

declare –a array=('aqsa' ‘rimsha’ ‘saeed’ ‘raza’ ‘awan’)
echo ${array[@]}

We will unset the value at index 2 from an array and declare another empty array named “array2”.

unset ‘array[2]
declare –a array2=()

After that, add an increment variable i=0, using the “for” loop to check the element in the first array and assign values of the first array to the second array, which is “array2”.

i=0
for element in ${array[@]}
do
array2[$i]=$element
((++i))
Done
echo ${array[@]}

When you print the old array again, it will not display the unset element but all other elements. Let’s try some echo statements to check whether the unset element is at its place or not. The first echo statement will display the message along with the specific index number value from an “array”. You can see that as the first value is already there in the array, it is displayed, and the second value is unsettled; therefore, it doesn’t display.

echo1<sup>st</sup> value is ${array[1]}, 2<sup>nd</sup> value is ${array[2]}

Another echo statement has been written out in which we have displayed the contents of the second array “array2” as:

echo ${array2[@]}

In the last and third echo statement, we have displayed the two specific values of the second array “array2” as:

echo1<sup>st</sup> value is ${array2[1]}, 2<sup>nd</sup> value is ${array2[2]}

On execution, you will get the below output.

Example 03: Remove an Element Using the Sub Arrays

In this example, we will be making new sub-arrays to remove an element from the specified array. The description of the below code is given.

Let’s define an array “arr” and assign it some values as below:

arr=( ‘e1’ ‘e2’ ‘e3’ ‘e4’ ‘e5’ ‘e6’)

Now print this array using the echo statement, and we will find the values of the array as output.

echo ${arr[@]}

The very crucial and important step of this method is to make sub-arrays of the defined array. So let us make two arrays from the old array using the indexes as:

arr=(${arr[@]:0:2}” “${arr[@]:3})

In the above code, we used the old array to define the new substring while setting the indexes. In “:0:2”, the first number after the colon represents the index value, which will be included in the sub-array, while the second index number after the colon will be excluded from the sub-array. This means that the new sub-array will not have the value of index 2 of real array “arr” which is “e3”. The “()” brackets are used to merge the sub-arrays and make a whole new array “arr” again. Now when you execute the file, it will display the old and new array as below.

echo ${arr[@]}

Conclusion

In this tutorial, we have efficiently tried three methods to remove an element from an array, e.g., using prefixes, unset, and sub-arrays. I hope this guide will help you understand removing an element from an array in bash.

]]>
Bash Variable Name Rules: Legal and Illegal https://linuxhint.com/bash-variable-name-rules-legal-illegal/ Thu, 18 Feb 2021 16:32:40 +0000 https://linuxhint.com/?p=90167 A variable is a storage space having a particular name that holds a certain value in it. You might have been working with a lot of programming languages and have a good perspective of variables. However, in the bash programming, it is slightly different. In this guide, we will learn about the rules invariable naming and execute some examples to declare a variable in a bash shell and observe its effect whether, it is valid or invalid, e.g., legal or illegal.

Legal Rules of Naming Variables in Bash

  • The variable name must be in the upper case as it is considered good practice in bash scripting.
  • Insert the dollar sign “$” before the variable name.
  • Don’t use spaces after the initialization of the variable name and its value.
  • A variable name can have letter/s.
  • A variable name can have numbers, underscores, and digits.

Illegal Rules of Name Variables in Bash

  • The variable name having lower case letters.
  • No dollar sign “$” inserted while printing it.
  • Adding spaces after the initialization of the variable name and its value.
  • Start the variable name with number, digit, or special symbols.
  • The variable name having space in it.
  • Use of keywords to name the variables, e.g., if, else, for, while, int, float, etc.

Example 01: Lower/Upper Case and Dollar Sign

Open your terminal and create a variable with an upper case. Print this variable using the statement “echo”, with and without dollar signs. Notice that with the “$” sign, it will display the value, otherwise, it will only display the variable name.

Example 02: Spaces after Variable Name and Equal Sign

Open your terminal and create a bash file named “variable.sh” using the touch command.

Open this file from the Home Directory and write the code as shown below. You can see that there are spaces after the variable name and equal sign, which is incorrect. On the other hand, a variable is not printed out without a dollar sign in the echo statement.

In the terminal, execute the bash command to run the file “variable.sh”. You will see that there is an error because of the invalid usage of rules.

Let’s correct the same code, with the dollar sign in the echo statement and no spaces in the variable name. Save and close it.

Again, running the file using the bash command, you can see that we have a valid output now.

You can also attempt it in a bash shell. Let’s take a variable with spaces before and after the equal sign. It will display an error, as shown below:

When you remove the spaces before and after the equal sign, it will be executed successfully. On the other hand, in bash, the variables are syntax sensitive, so make sure to run the correct variable. As you can see, when we print the lowercase variable, it will display its value, and on the usage of the uppercase variable, it will display nothing.

Example 03: Spaces in Variable Name

Let’s take the variable “ROLL NO” with spaces in between. It will display an error, as shown below. This means that the variable’s name cannot contain spaces.

When you remove the space, you can see it works correctly while using the echo statement and displays the value.

Example 04: Digits/Numbers in Variable Name

Let’s take a variable starting with some digit or number. As observed, it will display an error. This means that the variable name cannot have a number at the start. When you add a number in the middle or at the end of the variable, it will work correctly, as shown below. While using an echo statement, it will display the value of a variable name containing a number.

Take another example of using digit and number together. Declare a variable in the file “variable.sh” and print it out in the echo statement.

The bash command implies running the code. We will get an error due to the usage of digits and numbers at the start.

While correcting the variable, add the digit and number at the end of it and print it in an echo statement.

After doing so, it will work successfully and print the value of a variable.

Example 05: Special Characters in Variable Name

None of the special characters can be used in naming variables, e.g., asterisk, question mark, greater than, less than, hash, exclamation marks, etc. Let’s take an asterisk as an example. Even though we put it before, after, or in the middle of the name of a variable, it will cause an error generation. This means that no special character can be used in the variable name before, after, and in between.

Example 06: Underscore in Variable Name

The underscore can be used in naming variables before, after, and in between. Let’s have an example. While trying it before, after, and between the name of a variable, it will cause an error generation. This means that no special character can be used in the variable name before, after, and in between

In the bash file, we have declared a variable with an underscore in between the variable name. The echo statement has been used to print the variable.

Run the bash file using the bash command. You can see that the value has been printed out in the terminal correctly.

Example 07: Concatenate Variable with String

Let’s have an example of concatenating the variable with the string in the echo statement using the curly braces. Open the “variable.sh” and write the appended code in it. You can see that we have defined two variables. There is a new variable “WORK”. In the echo statement, we have a string text and a variable “WORK” within the curly brackets, then combined it with the text “ing”. Save and close it.

When you use the bash command to execute the “variable.sh” file in the command shell, we can see that the variable and string text has been concatenated successfully, and it displays: “The best job is Teaching”.

Conclusion

We have learned most of the variable naming rules for Bash scripting. Hopefully, you will be able to deal with naming variables within the rules.

]]>
How do I Increment a Variable in Bash? https://linuxhint.com/increment-a-variable-in-bash/ Wed, 17 Feb 2021 10:58:52 +0000 https://linuxhint.com/?p=90063 Incrementing or decrementing the value of a counter or an iterator is one of the most crucial tasks while using loops in any programming language. In doing so, it helps us reach the termination condition of our loop without which our loop will run infinitely. Today, our focus will be on the different methods of incrementing a variable in Bash in Linux Mint 20.

Examples of Incrementing a Variable in Bash in Linux Mint 20:

There are different ways of incrementing a variable in Bash. We will try to expand some of the most common ones through the examples below. However, we would like to introduce you to the concepts of pre- and post-increments. In the case of the former one, the value of a variable is incremented first and then assigned to another variable, whereas, in the latter, the value of a variable is stored first and is incremented afterward. The effects of both pre-increment and post-increment will be quite evident from the first two examples. So, let’s check out the example Bash scripts.

Example #1: Post-Incrementing a Variable:

To see the effect of post-increment, you must copy the script shown in the image below in any Bash file. You can create a Bash file in your Home directory with any name of your preference, then followed by a “.sh” extension.

In this script, we have declared a variable “x” and initialized it with the value “0”. Then we have another variable, “a”, where we assigned the post incremented value of the variable “x”. Finally, the value of the variable “a” on the terminal will be printed

To see the effect of this assignment on our output, we have to execute this script with the command shown below:

$ bash IncrementVariable.sh

Since we have post incremented the variable “x” and assigned it to the variable “a”, therefore, the value of variable “a” will still be “0”. It is so because the value of variable “x” (which was “0” initially) was first assigned to the variable “a” and then it was incremented. This output is shown in the following image:

Example #2: Pre-Incrementing a Variable:

Now, for checking the effect of pre-increment, we will use the same script as shown in the example above with a slight modification, which is shown in the image below:

In this script, instead of using post-increment, we simply used pre-increment. The remaining of the script is closely the same as example #1.

Now, when we execute this script, we will notice that the value of the variable “a” will be “1” instead of “0” because, this time, the value of the variable “x” was incremented first, and it was assigned to the variable “a”. This output is shown in the following image:

Example #3: Post-Incrementing a Variable within a “for” loop:

When you have clearly understood the concept of pre-increment and post-increment, we can use this concept within a “for” loop. The example script is shown in the image below:

In this script, there is a simple “for” loop with a counter variable or an iterator “i” whose value is being post incremented. Then we have simply printed the value of “i” for each iteration.

The output of this script is shown in the following image:

Example #4: Pre-Incrementing a Variable within a “for” loop:

For pre-incrementing a variable within a “for” loop, the example script is shown in the image below:

This script is the same as we did in example #3. The replacement of the post-increment with the pre-increment is the sole difference between the two scripts.

The output of this script is displayed in the appended image. This output is the same as the one shown in example #3, and you might be wondering why? It is so because this time, we are not assigning the value of the variable “i” to any other variable. That is why the effects of pre-increment and post-increment have become indistinguishable in these examples.

Example #5: Incrementing a Variable using “while” Loop with “+=” Notation:

The “+=” notation can also be used to increment the value of a variable and the example script demonstrated, this is shown in the image below:

In this script, we have declared a variable “i” and assigned the value “0”. Then we have a “while” loop that keeps iterating on this variable until its value is less than “5”. Within this loop, we are printing the value of this variable and then incrementing its value using the “+=” notation.

The output of this script is shown in the following image:

Example #6: Incrementing a Variable using “while” Loop with “+1” Notation:

The “+1” notation is also another way of incrementing the value of a variable by “1”. The example script demonstrating this is shown in the image below:

This script is the same as we did in example #5. The replacement of the “+=” notation with the “+1” notation is the sole difference between the two scripts.

The output of this script is shown in the following image:

Conclusion:

In today’s tutorial, we learned six different ways of incrementing a variable in Bash. We also threw light on the concepts of pre-increment and post-increment and illustrated these concepts using suitable examples. Depending upon the functionality that you require from your program, you can either choose to pre-increment or post-increment your counter variables or iterators. Using any of the ways of incrementing variables in Bash in Linux Mint 20, you can easily increase the value of your desired variables by “1”.

]]>
Creating Bash Infinite Loop by Example Scripts https://linuxhint.com/creating-bash-infinite-loop-by-example-scripts/ Sun, 14 Feb 2021 01:54:27 +0000 https://linuxhint.com/?p=89840 An infinite loop in Bash or any other programming language refers to a loop that is continuous i.e., its terminating condition is never met or its executing condition forever stays true. Such loops in any programming language are very simple to write. Whether it is a “for” loop or a “while” loop, it can be made infinite with very slight tweaking in its normal syntax.

In this article, we will be sharing with you the different ways on how you can conveniently make the “for” and “while” loops infinitely in Bash in Linux Mint 20.

Bash Infinite Loop Example Scripts in Linux Mint 20:

There are different ways of working with infinite loops in Bash, and the example scripts demonstrating these are described below:

Note: You can access all the Bash scripts discussed in this article in our Home Directory named InfiniteLoop.sh.

Script # 1: “While” Loop using the “:” Command in Bash in Linux Mint 20:

In this example, we will be creating a never-ending “while” loop by pairing it up with the “:” command in Bash in Linux Mint 20. Just copy the following script shown in the image in a Bash file.

As shown in the Bash script above, we have created a “while” loop followed by the “:” command. This command is an alternative to the “true” command, which means that no matter what the situation is “while” loop will always execute. Inside this “while” loop, we have simply printed a sample message that says, “Keep Running”. Afterward, we have the “sleep” command, it waits for 1 second before printing every next message on the terminal.

Once this Bash script is written, we will execute it with the command shown below:

$ bash InfiniteLoop.sh

When the said script is executed, you will notice unending messages saying, “Keep Running”, being displayed on your terminal, as shown in the following image. These messages will only stop if you press Ctrl+ C. Otherwise, this loop will just go on and on.

Script # 2: “While” Loop using the “true” Command in Bash in Linux Mint 20:

In this example, we will be creating a never-ending “while” loop by pairing it up with the “true” command in Bash in Linux Mint 20. Just simply copy the script shown in the image in a Bash file. As you can notice, the script is exactly the same as the one we created in the first scenario. However, the only difference is that this time, we have replaced the “:” command with the “true” command. Nonetheless, it will serve the exact same purpose.

We will execute this script with the same “bash” command, and we will notice a never-ending series of messages on our terminal, which will only terminate once we press Ctrl+ C, as shown in the image below:

Script # 3: One Liner “While” Loop using the “:” Command in Bash in Linux Mint 20:

You might observe that Script #1 and 3 are unnecessarily lengthy. Well, both of these scripts can be squeezed into a one-liner command. Just copy the script shown in the image below:

The script shown in the image above is the exact replication of Script # 1. However, instead of writing every command in a different line, we simply separated them using semi-colons.

When we execute this script, we will get the exact same results as we got after executing Script #1. This can be seen from the image shown below:

Script # 4: One Liner “While” Loop using the “true” Command in Bash in Linux Mint 20:

Similarly, we can squeeze Script #2 in a one-liner command. Just copy the script shown in the image below:

It can be observed that the script shown in the image above is the exact replication of Script #2. Again, the only difference is that instead of writing every command in a different line, we simply separated them using semi-colons.

When we execute this script, we will get the exact same results as we got after executing Script #2. This can be seen from the image shown below:

Script # 5: For Loop without any Parameters in Bash in Linux Mint 20:

This example is different from Scripts #1 to 4 because instead of using the “while” loop, we are going to create an infinite “for” loop. Just copy the script shown in the image below:

The task that we are going to perform inside the “for” loop is the same as we did with the scripts discussed above. However, instead of using the “while” loop, we have used the “for” loop without any conditions or parameters. It is always executed since its condition is considered “true” by default.

We will execute this script with the same “bash” command, and we will notice a never-ending series of messages on our terminal, which will only terminate once we press Ctrl+ C, as shown in the image below:

Conclusion:

In this article, we taught you five different ways of implementing infinite loops in Bash. These loops will keep on running forever since no terminating condition is specified, or even if there is, it is never going to meet. Therefore, if you want to put an end to this unending loop, you will either have to make use of a “break” statement with a specific condition within this loop or during the execution of such script, you have to simply press Ctrl+ C as we have discussed in all of our examples.

]]>
Exporting Bash Variables https://linuxhint.com/exporting-bash-variables/ Mon, 08 Feb 2021 16:08:36 +0000 https://linuxhint.com/?p=89403 Understanding variables in the Bash shell is essential in working with Linux in a professional manner. It is one of the key requirements for programming as well as achieving the Linux Professional Institute Certification (LPIC) Level 1 [2].

The previously published article by Fahmida Yesmin [4] gives you a wonderful introduction into Bash variables. Here we step further, and explain how to declare variables in Bash in such a way that you can use them in other environments on your Linux system, and which corresponding side effects you have to take into account.

A brief description of Bash

The Bash shell was first released in 1989 and has been used as the default login shell for most Linux distributions. Brian Fox wrote Bash as a UNIX shell and command language for the GNU Project as a free software replacement for the Bourne shell. It is an acronym for Bourne Again Shell. Bash is largely compatible with sh and incorporates useful features from the Korn shell ksh and the C shell csh [6].

While the GNU operating system provides other shells, including a version of csh, Bash is the default interactive shell. It is designed with portability in mind, and currently runs on nearly every version of UNIX plus other operating systems [9].

Bash variables in a nutshell

Variables are essential components of programming languages. They are referenced and manipulated in a computer program. Simply put, variables represent named memory cells. This is the same in Bash as in any programming language. This makes it possible for us as humans and users of the computer to store values in the “brain” of the computer and find them again via the assigned name of the variable.

The term variable refers to a combined form of two words, i.e., vary + able, which means its value can be changed, and it can be used for multiple times. In contrast to this, variables that cannot be changed are called constants. [10]

As long as there is enough memory available for your script you can freely create and use variables. You can simply set them by defining a variable name and then assigning its value. A variable name in Bash can include letters, digits, and underscores. Its name can be started with a letter and an underscore, only. Valid variable names are size, tax5, and _tax20 but not 5rules.

A variable value in Bash can contain a number, a single character, a string of characters, or a list of items (called array). It does not have a visible data type, and the internal data type of the variable will be automatically figured out (or derived) upon assignment of a value. Furthermore, there is no need to declare the variable — assigning a value to its reference will create the variable automatically. The example Bash script below demonstrates this for a string assignment, and a numeric number assignment.

#! /bin/bash


welcomeMessage="Hello World!"

echo $welcomeMessage


price=145

echo $price

Naming Conventions Of Bash Variables

There are no fixed rules for the spelling of names of variables, only conventions. These conventions are used:

  • Lowercase names — variables that are local to a script or function.
    No matter whether spelt lower_case/snake case [8], or camel case style [7]. The example above uses camel case style.
  • Uppercase names — constants, environment variables, shell built-in variables.
    Keep in mind that these variables might already be in use by other programs. Examples are $PATH, $LANG, $PWD, $PS4, and $SHELL.

For global IT companies it is common to work with style guides to ensure a common coding style among the company. See the Developer Editorial for IBM, and the Google Style Guide [3] for more information about the conventions they follow.

Variable Visibility

The default case is that a variable is locally bound to a structure, function, script, or process, and cannot be accessed from outside of it. The example below shows this for the variable $message that belongs to the script, and $welcome that belongs to the function outputWelcomeMessage().

#!/bin/bash


# define a variable message to the script

message=”Hello, again!


outputWelcomeMessage () {

    # define a local variable

    welcome=”Hello!

    echo $welcome

}


outputWelcomeMessage ()    # prints Hello!

echo $message              # prints Hello, again!

To make sure a previously defined variable with the same name is locally bound use the keyword local as demonstrated next. Without the keyword local the assignment in line 8 would relate to the globally defined variable with the same name defined earlier.

#!/bin/bash


# define a variable message to the script

message=”Hello, again!


outputWelcomeMessage () {

    # define a local variable with the same name

    Local message=”Hello!

    echo $message

}


outputWelcomeMessage ()    # prints Hello!

echo $message              # prints Hello, again!

Extending the scope of a variable

In order to make an internal variable visible to other child processes an additional step is needed. This step is called exporting a variable. Bash offers the usage of the keyword export followed by the variable name. The listing below demonstrates this for the variable backupPath.

$ backupPath=”/opt/backup/

$ export backupPath

The export command is a shell built-in that is used to define the variable as one that subshells (shells spawned from the original) inherit. Variables that are exported can be read and written by more than one process, then.

The second option is to declare the variable as an environment variable right from the start. You can do that by using the keyword declare followed by the option “-x” (see [5] for more info about the declare command). The effect is similar to the export command that was introduced before.

$ declare -x BACKUPPATH=”/opt/backup/

Inherit from other sessions

When you execute a program it automatically inherits its environment variables from the parent process. For instance if $HOME is set to /root in the parent then the child’s $HOME variable is also set to /root.

Further Commands

Among others, Linux comes with useful commands and options that relate to variables. The first two ones are called env and printenv. They list all the environment variables.

The image below shows the output of the command env in a terminal that is run in an X session. It contains variables like $XTERM (terminal type), $SHELL (the program that is called upon login, and shows /bin/bash for the path to the Bash interpreter), $LS_COLORS (the colours that are in use to highlight different file types when calling ls), and $DESKTOP_SESSION (the current X Desktop Environment).

The third and the fourth one are options of the export command — -p and -n. -p is short for print and just displays all the exported variables in the current shell using the declare command.

$ export -p

declare -x DESKTOP_SESSION="xfce"

declare -x DISPLAY=":0"

declare -x GLADE_CATALOG_PATH=":"

declare -x GLADE_MODULE_PATH=":"

declare -x GLADE_PIXMAP_PATH=":"

declare -x HOME="/home/frank"

declare -x LANG="de_DE.UTF-8"

The option -n is used to unset an environment variable. The listing below demonstrates this for the previously defined variable BACKUPPATH.

$ export -n BACKUPPATH

Conclusion

Bash is a very clever but sometimes also a bit complex environment. Variables control how the different tools interact. Exporting variables helps communicating between processes and is easy to use in everyday life.

About the authors

Jacqui Kabeta is an environmentalist, avid researcher, trainer and mentor. In several African countries she has worked in the IT industry and NGO environments.

Frank Hofmann is an IT developer, trainer, and author and prefers to work from Berlin, Geneva and Cape Town. Co-author of the Debian Package Management Book available from dpmb.org

Links and References

]]>
A Simple Guide to Create, Open, and Edit bash_profile https://linuxhint.com/simple-guide-to-create-open-edit-bash-profile/ Tue, 05 Jan 2021 15:41:25 +0000 https://linuxhint.com/?p=84482 The .bash_profile is used for customizing the user configuration settings. This file is located in the home directory and is mostly hidden. The .bash_profile files are considered as configuration scripts. They can include variable specifications, export variables, and login commands such as mail or news search.

Create the .bash_profile File

Open the command by a shortcut key Ctrl+Alt+T or from the side icon of the terminal. The command is now opened. First of all, you need to create a .bash_profile file using a touch command in the terminal shown below:

$ touch .bash_profile

This is the simplest way to create a file in a terminal, and it will not display any message that a file has been created.

List the .bash_profile File

When you search for the .bash_profile by checking it in File Explorer, you cannot find the file because it is hidden. On the other hand, you can search for the newly created .bash_profile file using the list command as:

$ ls –la

Open the .bash_profile File

To open the newly created .bash_profile from the terminal, we need to simply write the nano keyword command as follows:

$ nano .bash_profile


You will see the .bash_profile file will be opened in a new window. It has different keys listed at the bottom, with the file name displayed at the top center of the file window.

Edit the .bash_profile File

Now, if you want to check whether any data or information written in this profile will be displayed on the terminal upon calling, you can do so. For that, you have to write some code in the .bash_profile file. Write the echo statement with the ‘FROM BASH_PROFILE’ in single inverted commas. Save this file using the Ctrl+S key followed by tapping Y. After that, close this file by pressing Ctrl+X, and you will be navigated to the terminal again.

Display the .bash_profile Changes

Now, to implement the changes of this file and to check the outcome of the statement written in the .bash_profile, we need to write the simple source command in the terminal as:

$ source .bash_profile

You will see the text written in the single inverted commas will be displayed in the terminal.


To do some extra customization, try some other things as well. So make a new .bashrc file using the touch command and open it using the nano command as:

$ touch .bashrc
$ nano .bashrc

Scroll down to the bottom and add some echo statement in it with some text in single inverted commas. Save this file using Ctrl+S followed by tapping the Y key. You can close this file using the Ctrl+X key.


Now open the .bash_profile again from the terminal using the nano execution command.

$ nano .bash_profile


Write down the below-shown statements in the .bash_profile file. You can avoid the hash sign statements because they are usually comments. In the ‘if’ statement, ‘-f’ refers to the existence of this file. This means that if the .bashrc file exists, then do the following action. On the next line, the dot followed by the listed filename refers to open this file. Now, save this file using Ctrl+S followed by the Y key. Close it using CTrl+X.


Try the source command again for the .bash_profile file. This will execute the .bash_profile file, and will obviously execute the .bashrc file because the .bashrc file is linked to the .bash_profile file.

$ source .bash_profile

Every time you open the terminal, you will see the text displayed on its top corner. This text is written in the .bashrc file due to the linkage of files.


Open the .bash_profile file and set the PATH variable in it, as displayed in the image, and export this variable using the export keyword. Save this file and exit.


In the command terminal, write the echo statement followed by the PATH variable. You will see it will display the random different path locations. These locations are mostly those that are having any script file in them. The script file means any login script from which you can update your password.

$ echo $PATH


So when you add the password command in the terminal, it will display the text as ‘ Changing password for Username’. After that, it will ask for your current user password. So, add your current password. Then, it will ask for your new password followed by retyping the new password. Through this method, you can change your login credentials for the current user.

$ passwd


Again, open the .bash_profile file using the nano command.

$ nano .bash_profile

Add some extra echo statements in this file. After that, add another statement having initials PS1 followed by = sign. In the inverted commas, add backslash followed by the alphabet W and greater then > sign. This means that when the .bash_profile file has been executed, it will customize the command terminal by providing the space for commands. Save and close this file.


When you run this file using the source command, you will be able to see the text written in the echo statements as output. You will see another change, which is due to the PS1 statement. This change is ~> sign, which is used for adding new commands.


Now add the cd command followed by double dots in this newly customized terminal. It will direct you to the home directory, which is our set PATH. Again adding a cd command followed by double dots will direct you to the file system of Linux home. When you try the list command in the terminal, it will display the list of folders.


Try the cd command followed by the ‘~’ sign, and it will direct you to the main directory. When you list the directories, it will display the below output.

Conclusion

In this guide, you have learned how the users usually do things like: add some directory to variable $PATH, export any variable, modify $PS1, set view colors, add a welcome text message, etc.

]]>