LinuxSimply

Home > Bash Scripting Tutorial > Bash Variables > Variable Declaration and Assignment > How to Assign Variable in Bash Script? [8 Practical Cases]

How to Assign Variable in Bash Script? [8 Practical Cases]

Mohammad Shah Miran

Variables allow you to store and manipulate data within your script, making it easier to organize and access information. In Bash scripts , variable assignment follows a straightforward syntax, but it offers a range of options and features that can enhance the flexibility and functionality of your scripts. In this article, I will discuss modes to assign variable in the Bash script . As the Bash script offers a range of methods for assigning variables, I will thoroughly delve into each one.

Table of Contents

Key Takeaways

  • Getting Familiar With Different Types Of Variables.
  • Learning how to assign single or multiple bash variables.
  • Understanding the arithmetic operation in Bash Scripting.

Free Downloads

Local vs global variable assignment.

In programming, variables are used to store and manipulate data. There are two main types of variable assignments: local and global .

A. Local Variable Assignment

In programming, a local variable assignment refers to the process of declaring and assigning a variable within a specific scope, such as a function or a block of code. Local variables are temporary and have limited visibility, meaning they can only be accessed within the scope in which they are defined.

Here are some key characteristics of local variable assignment:

  • Local variables in bash are created within a function or a block of code.
  • By default, variables declared within a function are local to that function.
  • They are not accessible outside the function or block in which they are defined.
  • Local variables typically store temporary or intermediate values within a specific context.

Here is an example in Bash script.

In this example, the variable x is a local variable within the scope of the my_function function. It can be accessed and used within the function, but accessing it outside the function will result in an error because the variable is not defined in the outer scope.

B. Global Variable Assignment

In Bash scripting, global variables are accessible throughout the entire script, regardless of the scope in which they are declared. Global variables can be accessed and modified from any script part, including within functions.

Here are some key characteristics of global variable assignment:

  • Global variables in bash are declared outside of any function or block.
  • They are accessible throughout the entire script.
  • Any variable declared outside of a function or block is considered global by default.
  • Global variables can be accessed and modified from any script part, including within functions.

Here is an example in Bash script given in the context of a global variable .

It’s important to note that in bash, variable assignment without the local keyword within a function will create a global variable even if there is a global variable with the same name. To ensure local scope within a function , using the local keyword explicitly is recommended.

Additionally, it’s worth mentioning that subprocesses spawned by a bash script, such as commands executed with $(…) or backticks , create their own separate environments, and variables assigned within those subprocesses are not accessible in the parent script .

8 Different Cases to Assign Variables in Bash Script

In Bash scripting , there are various cases or scenarios in which you may need to assign variables. Here are some common cases I have described below. These examples cover various scenarios, such as assigning single variables , multiple variable assignments in a single line , extracting values from command-line arguments , obtaining input from the user , utilizing environmental variables, etc . So let’s start.

Case 01: Single Variable Assignment

To assign a value to a single variable in Bash script , you can use the following syntax:

However, replace the variable with the name of the variable you want to assign, and the value with the desired value you want to assign to that variable.

To assign a single value to a variable in Bash , you can go in the following manner:

Steps to Follow >

❶ At first, launch an Ubuntu Terminal .

❷ Write the following command to open a file in Nano :

  • nano : Opens a file in the Nano text editor.
  • single_variable.sh : Name of the file.

❞ Copy the script mentioned below:

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. Next, variable var_int contains an integer value of 23 and displays with the echo command .

âč Press CTRL+O and ENTER to save the file; CTRL+X to exit.

âș Use the following command to make the file executable :

  • chmod : changes the permissions of files and directories.
  • u+x : Here, u refers to the “ user ” or the owner of the file and +x specifies the permission being added, in this case, the “ execute ” permission. When u+x is added to the file permissions, it grants the user ( owner ) permission to execute ( run ) the file.
  • single_variable.sh : File name to which the permissions are being applied.

❻ Run the script by using the following command:

Single Variable Assignment

Case 02: Multi-Variable Assignment in a Single Line of a Bash Script

Multi-variable assignment in a single line is a concise and efficient way of assigning values to multiple variables simultaneously in Bash scripts . This method helps reduce the number of lines of code and can enhance readability in certain scenarios. Here’s an example of a multi-variable assignment in a single line.

You can follow the steps of Case 01 , to save & make the script executable.

Script (multi_variable.sh) >

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. Then, three variables x , y , and z are assigned values 1 , 2 , and 3 , respectively. The echo statements are used to print the values of each variable. Following that, two variables var1 and var2 are assigned values “ Hello ” and “ World “, respectively. The semicolon (;) separates the assignment statements within a single line. The echo statement prints the values of both variables with a space in between. Lastly, the read command is used to assign values to var3 and var4. The <<< syntax is known as a here-string , which allows the string “ Hello LinuxSimply ” to be passed as input to the read command . The input string is split into words, and the first word is assigned to var3 , while the remaining words are assigned to var4 . Finally, the echo statement displays the values of both variables.

Multi-Variable Assignment in a Single Line of a Bash Script

Case 03: Assigning Variables From Command-Line Arguments

In Bash , you can assign variables from command-line arguments using special variables known as positional parameters . Here is a sample code demonstrated below.

Script (var_as_argument.sh) >

Assigning Variables from Command-Line Arguments

Case 04: Assign Value From Environmental Bash Variable

In Bash , you can also assign the value of an Environmental Variable to a variable. To accomplish the task you can use the following syntax :

However, make sure to replace ENV_VARIABLE_NAME with the actual name of the environment variable you want to assign. Here is a sample code that has been provided for your perusal.

Script (env_variable.sh) >

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. The value of the USER environment variable, which represents the current username, is assigned to the Bash variable username. Then the output is displayed using the echo command.

Assign Value from Environmental Bash Variable

Case 05: Default Value Assignment

In Bash , you can assign default values to variables using the ${variable:-default} syntax . Note that this default value assignment does not change the original value of the variable; it only assigns a default value if the variable is empty or unset . Here’s a script to learn how it works.

Script (default_variable.sh) >

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. The next line stores a null string to the variable . The ${ variable:-Softeko } expression checks if the variable is unset or empty. As the variable is empty, it assigns the default value ( Softeko in this case) to the variable . In the second portion of the code, the LinuxSimply string is stored as a variable. Then the assigned variable is printed using the echo command .

Default Value Assignment

Case 06: Assigning Value by Taking Input From the User

In Bash , you can assign a value from the user by using the read command. Remember we have used this command in Case 2 . Apart from assigning value in a single line, the read command allows you to prompt the user for input and assign it to a variable. Here’s an example given below.

Script (user_variable.sh) >

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. The read command is used to read the input from the user and assign it to the name variable . The user is prompted with the message “ Enter your name: “, and the value they enter is stored in the name variable. Finally, the script displays a message using the entered value.

Assigning Value by Taking Input from the User

Case 07: Using the “let” Command for Variable Assignment

In Bash , the let command can be used for arithmetic operations and variable assignment. When using let for variable assignment, it allows you to perform arithmetic operations and assign the result to a variable .

Script (let_var_assign.sh) >

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. then the let command performs arithmetic operations and assigns the results to variables num. Later, the echo command has been used to display the value stored in the num variable.

Using the let Command for Variable Assignment

Case 08: Assigning Shell Command Output to a Variable

Lastly, you can assign the output of a shell command to a variable using command substitution . There are two common ways to achieve this: using backticks ( “) or using the $()   syntax. Note that $() syntax is generally preferable over backticks as it provides better readability and nesting capability, and it avoids some issues with quoting. Here’s an example that I have provided using both cases.

Script (shell_command_var.sh) >

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. The output of the ls -l command (which lists the contents of the current directory in long format) allocates to the variable output1 using backticks . Similarly, the output of the date command (which displays the current date and time) is assigned to the variable output2 using the $() syntax . The echo command displays both output1 and output2 .

Assigning Shell Command Output to a Variable

Assignment on Assigning Variables in Bash Scripts

Finally, I have provided two assignments based on today’s discussion. Don’t forget to check this out.

  • Difference: ?
  • Quotient: ?
  • Remainder: ?
  • Write a Bash script to find and display the name of the largest file using variables in a specified directory.

In conclusion, assigning variable Bash is a crucial aspect of scripting, allowing developers to store and manipulate data efficiently. This article explored several cases to assign variables in Bash, including single-variable assignments , multi-variable assignments in a single line , assigning values from environmental variables, and so on. Each case has its advantages and limitations, and the choice depends on the specific needs of the script or program. However, if you have any questions regarding this article, feel free to comment below. I will get back to you soon. Thank You!

People Also Ask

Related Articles

  • How to Declare Variable in Bash Scripts? [5 Practical Cases]
  • Bash Variable Naming Conventions in Shell Script [6 Rules]
  • How to Check Variable Value Using Bash Scripts? [5 Cases]
  • How to Use Default Value in Bash Scripts? [2 Methods]
  • How to Use Set – $Variable in Bash Scripts? [2 Examples]
  • How to Read Environment Variables in Bash Script? [2 Methods]
  • How to Export Environment Variables with Bash? [4 Examples]

<< Go Back to Variable Declaration and Assignment  | Bash Variables | Bash Scripting Tutorial

Mohammad Shah Miran

Mohammad Shah Miran

Hey, I'm Mohammad Shah Miran, previously worked as a VBA and Excel Content Developer at SOFTEKO, and for now working as a Linux Content Developer Executive in LinuxSimply Project. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). As a part of my job, i communicate with Linux operating system, without letting the GUI to intervene and try to pass it to our audience.

Leave a Comment Cancel reply

Save my name, email, and website in this browser for the next time I comment.

linuxsimply white logo

Get In Touch!

card

Legal Corner

dmca

Copyright © 2024 LinuxSimply | All Rights Reserved.

How-To Geek

How to work with variables in bash.

4

Your changes have been saved

Email is sent

Email has already been sent

Please verify your email address.

You’ve reached your account maximum for followed topics.

Hannah Stryker / How-To Geek

Quick Links

What is a variable in bash, examples of bash variables, how to use bash variables in scripts, how to use command line parameters in scripts, working with special variables, environment variables, how to export variables, how to quote variables, echo is your friend, key takeaways.

  • Variables are named symbols representing strings or numeric values. They are treated as their value when used in commands and expressions.
  • Variable names should be descriptive and cannot start with a number or contain spaces. They can start with an underscore and can have alphanumeric characters.
  • Variables can be used to store and reference values. The value of a variable can be changed, and it can be referenced by using the dollar sign $ before the variable name.

Variables are vital if you want to write scripts and understand what that code you're about to cut and paste from the web will do to your Linux computer. We'll get you started!

Variables are named symbols that represent either a string or numeric value. When you use them in commands and expressions, they are treated as if you had typed the value they hold instead of the name of the variable.

To create a variable, you just provide a name and value for it. Your variable names should be descriptive and remind you of the value they hold. A variable name cannot start with a number, nor can it contain spaces. It can, however, start with an underscore. Apart from that, you can use any mix of upper- and lowercase alphanumeric characters.

Here, we'll create five variables. The format is to type the name, the equals sign = , and the value. Note there isn't a space before or after the equals sign. Giving a variable a value is often referred to as assigning a value to the variable.

We'll create four string variables and one numeric variable,

my_name=Dave

my_boost=Linux

his_boost=Spinach

this_year=2019

To see the value held in a variable, use the echo command. You must precede the variable name with a dollar sign $ whenever you reference the value it contains, as shown below:

echo $my_name

echo $my_boost

echo $this_year

Let's use all of our variables at once:

echo "$my_boost is to $me as $his_boost is to $him (c) $this_year"

The values of the variables replace their names. You can also change the values of variables. To assign a new value to the variable, my_boost , you just repeat what you did when you assigned its first value, like so:

my_boost=Tequila

If you re-run the previous command, you now get a different result:

So, you can use the same command that references the same variables and get different results if you change the values held in the variables.

We'll talk about quoting variables later. For now, here are some things to remember:

  • A variable in single quotes ' is treated as a literal string, and not as a variable.
  • Variables in quotation marks " are treated as variables.
  • To get the value held in a variable, you have to provide the dollar sign $ .
  • A variable without the dollar sign $ only provides the name of the variable.

You can also create a variable that takes its value from an existing variable or number of variables. The following command defines a new variable called drink_of_the_Year, and assigns it the combined values of the my_boost and this_year variables:

drink_of-the_Year="$my_boost $this_year"

echo drink_of_the-Year

Scripts would be completely hamstrung without variables. Variables provide the flexibility that makes a script a general, rather than a specific, solution. To illustrate the difference, here's a script that counts the files in the /dev directory.

Type this into a text file, and then save it as fcnt.sh (for "file count"):

#!/bin/bashfolder_to_count=/devfile_count=$(ls $folder_to_count | wc -l)echo $file_count files in $folder_to_count

Before you can run the script, you have to make it executable, as shown below:

chmod +x fcnt.sh

Type the following to run the script:

This prints the number of files in the /dev directory. Here's how it works:

  • A variable called folder_to_count is defined, and it's set to hold the string "/dev."
  • Another variable, called file_count , is defined. This variable takes its value from a command substitution. This is the command phrase between the parentheses $( ) . Note there's a dollar sign $ before the first parenthesis. This construct $( ) evaluates the commands within the parentheses, and then returns their final value. In this example, that value is assigned to the file_count variable. As far as the file_count variable is concerned, it's passed a value to hold; it isn't concerned with how the value was obtained.
  • The command evaluated in the command substitution performs an ls file listing on the directory in the folder_to_count variable, which has been set to "/dev." So, the script executes the command "ls /dev."
  • The output from this command is piped into the wc command. The -l (line count) option causes wc to count the number of lines in the output from the ls command. As each file is listed on a separate line, this is the count of files and subdirectories in the "/dev" directory. This value is assigned to the file_count variable.
  • The final line uses echo to output the result.

But this only works for the "/dev" directory. How can we make the script work with any directory? All it takes is one small change.

Many commands, such as ls and wc , take command line parameters. These provide information to the command, so it knows what you want it to do. If you want ls to work on your home directory and also to show hidden files , you can use the following command, where the tilde ~ and the -a (all) option are command line parameters:

Our scripts can accept command line parameters. They're referenced as $1 for the first parameter, $2 as the second, and so on, up to $9 for the ninth parameter. (Actually, there's a $0 , as well, but that's reserved to always hold the script.)

You can reference command line parameters in a script just as you would regular variables. Let's modify our script, as shown below, and save it with the new name fcnt2.sh :

#!/bin/bashfolder_to_count=$1file_count=$(ls $folder_to_count | wc -l)echo $file_count files in $folder_to_count

This time, the folder_to_count variable is assigned the value of the first command line parameter, $1 .

The rest of the script works exactly as it did before. Rather than a specific solution, your script is now a general one. You can use it on any directory because it's not hardcoded to work only with "/dev."

Here's how you make the script executable:

chmod +x fcnt2.sh

Now, try it with a few directories. You can do "/dev" first to make sure you get the same result as before. Type the following:

./fnct2.sh /dev

./fnct2.sh /etc

./fnct2.sh /bin

You get the same result (207 files) as before for the "/dev" directory. This is encouraging, and you get directory-specific results for each of the other command line parameters.

To shorten the script, you could dispense with the variable, folder_to_count , altogether, and just reference $1 throughout, as follows:

#!/bin/bash file_count=$(ls $1 wc -l) echo $file_count files in $1

We mentioned $0 , which is always set to the filename of the script. This allows you to use the script to do things like print its name out correctly, even if it's renamed. This is useful in logging situations, in which you want to know the name of the process that added an entry.

The following are the other special preset variables:

  • $# : How many command line parameters were passed to the script.
  • $@ : All the command line parameters passed to the script.
  • $? : The exit status of the last process to run.
  • $$ : The Process ID (PID) of the current script.
  • $USER : The username of the user executing the script.
  • $HOSTNAME : The hostname of the computer running the script.
  • $SECONDS : The number of seconds the script has been running for.
  • $RANDOM : Returns a random number.
  • $LINENO : Returns the current line number of the script.

You want to see all of them in one script, don't you? You can! Save the following as a text file called, special.sh :

#!/bin/bashecho "There were $# command line parameters"echo "They are: $@"echo "Parameter 1 is: $1"echo "The script is called: $0"# any old process so that we can report on the exit statuspwdecho "pwd returned $?"echo "This script has Process ID $$"echo "The script was started by $USER"echo "It is running on $HOSTNAME"sleep 3echo "It has been running for $SECONDS seconds"echo "Random number: $RANDOM"echo "This is line number $LINENO of the script"

Type the following to make it executable:

chmod +x special.sh

Now, you can run it with a bunch of different command line parameters, as shown below.

Bash uses environment variables to define and record the properties of the environment it creates when it launches. These hold information Bash can readily access, such as your username, locale, the number of commands your history file can hold, your default editor, and lots more.

To see the active environment variables in your Bash session, use this command:

If you scroll through the list, you might find some that would be useful to reference in your scripts.

When a script runs, it's in its own process, and the variables it uses cannot be seen outside of that process. If you want to share a variable with another script that your script launches, you have to export that variable. We'll show you how to this with two scripts.

First, save the following with the filename script_one.sh :

#!/bin/bashfirst_var=alphasecond_var=bravo# check their valuesecho "$0: first_var=$first_var, second_var=$second_var"export first_varexport second_var./script_two.sh# check their values againecho "$0: first_var=$first_var, second_var=$second_var"

This creates two variables, first_var and second_var , and it assigns some values. It prints these to the terminal window, exports the variables, and calls script_two.sh . When script_two.sh terminates, and process flow returns to this script, it again prints the variables to the terminal window. Then, you can see if they changed.

The second script we'll use is script_two.sh . This is the script that script_one.sh calls. Type the following:

#!/bin/bash# check their valuesecho "$0: first_var=$first_var, second_var=$second_var"# set new valuesfirst_var=charliesecond_var=delta# check their values againecho "$0: first_var=$first_var, second_var=$second_var"

This second script prints the values of the two variables, assigns new values to them, and then prints them again.

To run these scripts, you have to type the following to make them executable:

chmod +x script_one.shchmod +x script_two.sh

And now, type the following to launch script_one.sh :

./script_one.sh

This is what the output tells us:

  • script_one.sh prints the values of the variables, which are alpha and bravo.
  • script_two.sh prints the values of the variables (alpha and bravo) as it received them.
  • script_two.sh changes them to charlie and delta.
  • script_one.sh prints the values of the variables, which are still alpha and bravo.

What happens in the second script, stays in the second script. It's like copies of the variables are sent to the second script, but they're discarded when that script exits. The original variables in the first script aren't altered by anything that happens to the copies of them in the second.

You might have noticed that when scripts reference variables, they're in quotation marks " . This allows variables to be referenced correctly, so their values are used when the line is executed in the script.

If the value you assign to a variable includes spaces, they must be in quotation marks when you assign them to the variable. This is because, by default, Bash uses a space as a delimiter.

Here's an example:

site_name=How-To Geek

Bash sees the space before "Geek" as an indication that a new command is starting. It reports that there is no such command, and abandons the line. echo shows us that the site_name variable holds nothing — not even the "How-To" text.

Try that again with quotation marks around the value, as shown below:

site_name="How-To Geek"

This time, it's recognized as a single value and assigned correctly to the site_name variable.

It can take some time to get used to command substitution, quoting variables, and remembering when to include the dollar sign.

Before you hit Enter and execute a line of Bash commands, try it with echo in front of it. This way, you can make sure what's going to happen is what you want. You can also catch any mistakes you might have made in the syntax.

  • Linux & macOS Terminal

Tecmint: Linux Howtos, Tutorials & Guides

How To Assign Output of a Linux Command to a Variable

When you run a command, it produces some kind of output: either the result of a program is suppose to produce or status/error messages of the program execution details. Sometimes, you may want to store the output of a command in a variable to be used in a later operation.

In this post, we will review the different ways of assigning the output of a shell command to a variable, specifically useful for shell scripting purpose.

To store the output of a command in a variable, you can use the shell command substitution feature in the forms below:

Below are a few examples of using command substitution.

In this first example, we will store the value of who (which shows who is logged on the system) command in the variable CURRENT_USERS user:

Then we can use the variable in a sentence displayed using the echo command like so:

In the command above: the flag -e means interpret any escape sequences ( such as \n for newline) used. To avoid wasting time as well as memory, simply perform the command substitution within the echo command as follows:

Shows Current Logged Users in Linux

Next, to demonstrate the concept using the second form; we can store the total number of files in the current working directory in a variable called FILES and echo it later as follows:

Show Number of Files in Directory

That’s it for now, in this article, we explained the methods of assigning the output of a shell command to a variable. You can add your thoughts to this post via the feedback section below.

Hey TecMint readers ,

Exciting news! Every month, our top blog commenters will have the chance to win fantastic rewards, like free Linux eBooks such as RHCE , RHCSA , LFCS , Learn Linux , and Awk , each worth $20 !

Learn more about the contest and stand a chance to win by sharing your thoughts below !

assignment command in shell

Previous article:

Next article:

Photo of author

Each tutorial at TecMint is created by a team of experienced Linux system administrators so that it meets our high-quality standards.

Related Posts

Dtrx Linux Archive Tool

Dtrx – An Intelligent Archive Extraction (tar, zip, cpio, rpm, deb, rar) Tool for Linux

X Window Linux Commands

7 Useful X-Window (GUI-Based) Linux Commands – Part 2

X-Based Commands in Linux

11 Useful X-window (GUI Based) Linux Commands – Part I

diff3 command in linux

How to Use diff3 Command for File Merging in Linux

Convert SVG to PNG in Linux

How to Convert SVG to PNG in Linux

Set Temporary Static IP in Linux

How to Temporarily Set a Static IP Address on a Linux System

10 Comments

In my case it does not work for:

The command module list python writes to the command line:

Currently Loaded Modules Matching: python/3.7.4

You missed process substitution. For example: read uid gid < <(grep ^root /etc/passwd | awk -F: '{print $3 " " $4}') This allows you to set 2 or more variables if you mant.

Yap, how did i forget to mention this, it’s so helpful while writing scripts. Thanks for the reminder.

Why is $(…) preferred over `…` (backticks): http://mywiki.wooledge.org/BashFAQ/082

Many thanks for providing this useful link.

From the link Above “The backtick is also easily confused with a single quote.”

This happened in this article for the first figure.

@Depressing

True, it was a typo during publishing. We will modify the article as soon as possible. Thanks for the feedback.

Is there a way to store the result of the command ONLY if there is no error during the command ?

That is exactly what we explained in the article. To separate the result of a command from error messages, you can perform output/error redirection to files other than the screen. Then read the result from the file.

Read more about output redirection from here: https://www.tecmint.com/linux-io-input-output-redirection-operators/

Got Something to Say? Join the Discussion... Cancel reply

Thank you for taking the time to share your thoughts with us. We appreciate your decision to leave a comment and value your contribution to the discussion. It's important to note that we moderate all comments in accordance with our comment policy to ensure a respectful and constructive conversation.

Rest assured that your email address will remain private and will not be published or shared with anyone. We prioritize the privacy and security of our users.

Save my name, email, and website in this browser for the next time I comment.

  • Shell Scripting
  • Docker in Linux
  • Kubernetes in Linux
  • Linux interview question

Shell Script Examples

For all the Linux distributions, the shell script is like a magic wand that automates the process, saves users time, and increases productivity. This shall scripting tutorial will introduce you to the 25 plus shall scripting examples.

But before we move on to the topic of shell scripting examples, let’s understand shell script and the actual use cases of shell scripting.

What is Shell Script?

Well, the shell is a CLI ( command line interpreter ), which runs in a text window where users can manage and execute shell commands. On the other hand, the process of writing a set of commands to be executed on a Linux system A file that includes such instructions is called a bash script.

Uses of Shell Scripts

Below are some common uses of Shell Script:

  • Task Automation – It can be used to automate repetitive tasks like regular backups and software installation tasks.
  • Customization – One can use shell scripts to design its command line environment and easily perform its task as per needs.
  • File Management – The shell scripts can also be used to manage and manipulate files and directories, such as moving, copying, renaming, or deleting files.

Shell Script Examples in Linux

1) what does the shebang (#) at the beginning of a shell script indicate.

The shebang (#!) at the beginning of a script indicates the interpreter that should be used to execute the script. It tells the system which shell or interpreter should interpret the script’s commands.

For example: Suppose we have a script named myscript.sh written in the Bash shell:

shebang

In this example:

  • The #!/bin/bash at the beginning of the script indicates that the script should be interpreted using the Bash shell.
  • The echo commands are used to print messages to the terminal.

2) How do you run a shell script from the command line?

To run a shell script from the command line, we need to follow these steps:

  • Make sure the script file has executable permissions using the chmod command :
  • Execute the script using its filename:

Here you have to replace “ myscrtipt.sh ” with yors script name.

3) Write a shell script that prints “GeeksforGeeks” to the terminal.

Create a script name `myscript.sh` (we are using ` vim ` editor, you can choose any editor)

#!/bin/bash # This script prints “GeeksforGeeks” to the terminal echo “GeeksforGeeks”

print name

We make our script executable by using `chmod +x` then execute with `./myscipt.sh` and get our desired output “GeeksforGeeks”.

4) Explain the purpose of the echo command in shell scripting.

The echo command is used to display text or variables on the terminal. It’s commonly used for printing messages, variable values, and generating program output.

434

echo command

In this example we have execute `echo` on terminal directely , as it works same inside shell script.

5) How can you assign a value to a variable in a shell script?

Variables are assigned values using the assignment operator =.

For example:

#!/bin/bash # Assigning a value to a variable name=”Jayesh” age=21 echo $name $age

Explanation:

  • The name variable is assigned the value “Jayesh”.
  • The age variable is assigned the value 21.
  • echo is used to print and `$name` `$age` is used to call the value stored in the variables.

435

6) Write a shell script that takes a user’s name as input and greets them.

Create a script name `example.sh`.

#!/bin/bash # Ask the user for their name echo “What’s your name?” read name # Greet the user echo “Hello, $name! Nice to meet you.”
  • #!/bin/bash: This is the shebang line. It tells the system to use the Bash interpreter to execute the script.
  • # Ask the user for their name: This is a comment. It provides context about the upcoming code. Comments are ignored by the interpreter.
  • echo “What’s your name?”: The echo command is used to display the text in double quotes on the terminal.
  • read name: The read command waits for the user to input text and stores it in the variable name.
  • echo “Hello, $name! Nice to meet you.”: This line uses the echo command to print a greeting message that includes the value of the name variable, which was collected from the user’s input.

436

7) How do you add comments to a shell script?

Comments in shell scripting are used to provide explanations or context to the code. They are ignored by the interpreter and are only meant for humans reading the script. You can add comments using the # symbol.

#!/bin/bash # This is a comment explaining the purpose of the script echo “gfg”

8) Create a shell script that checks if a file exists in the current directory.

Here’s a script that checks if a file named “example.txt” exists in the current directory:

#!/bin/bash file=”example.txt” # Check if the file exists if [ -e “$file” ]; then echo “File exists: $file” else echo “File not found: $file” fi
  • #!/bin/bash: This is the shebang line that specifies the interpreter (/bin/bash) to be used for running the script.
  • file=”example.txt”: This line defines the variable file and assigns the value “example.txt” to it. You can replace this with the name of the file you want to check for.
  • if [ -e “$file” ]; then: This line starts an if statement. The condition [ -e “$file” ] checks if the file specified by the value of the file variable exists. The -e flag is used to check for file existence.
  • echo “File exists: $file”: If the condition is true (i.e., the file exists), this line prints a message indicating that the file exists, along with the file’s name.
  • else: If the condition is false (i.e., the file doesn’t exist), the script executes the code under the else branch.
  • echo “File not found: $file”: This line prints an error message indicating that the specified file was not found, along with the file’s name.
  • fi: This line marks the end of the if statement.

Finding file

Finding file

9) What is the difference between single quotes (‘) and double quotes (“) in shell scripting?

Single quotes (‘) and double quotes (“) are used to enclose strings in shell scripting, but they have different behaviors:

  • Single quotes: Everything between single quotes is treated as a literal string. Variable names and most special characters are not expanded.
  • Double quotes: Variables and certain special characters within double quotes are expanded. The contents are subject to variable substitution and command substitution.
#!/bin/bash abcd=”Hello” echo ‘$abcd’ # Output: $abcd echo “$abcd” # Output: Hello

10) How can you use command-line arguments in a shell script?

Command-line arguments are values provided to a script when it’s executed. They can be accessed within the script using special variables like $1, $2, etc., where $1 represents the first argument, $2 represents the second argument, and so on.

For Example: If our script name in `example.sh`

#!/bin/bash echo “Script name: $0” echo “First argument: $1” echo “Second argument: $2”

If we run the script with `.example.sh hello_1 hello_2`, it will output:

cli arguments

cli arguments

11) How do you use the for loop to iterate through a list of values?

#!/bin/bash fruits=(“apple” “banana” “cherry” “date”) for fruit in “${fruits[@]}”; do echo “Current fruit: $fruit” done

`fruits=` line creates an array named fruits with four elements: “apple”, “banana”, “cherry”, and “date”.

  • for fruit in “${fruits[@]}”; do: This line starts a for loop. Here’s what each part means:
  • for fruit: This declares a loop variable called fruit. In each iteration of the loop, fruit will hold the value of the current element from the fruits array.
  • “${fruits[@]}”: This is an array expansion that takes all the elements from the fruits array. The “${…}” syntax ensures that each element is treated as a separate item.
  • do: This keyword marks the beginning of the loop body.
  • echo “Current fruit: $fruit”: Inside the loop, this line uses the echo command to display the current value of the loop variable fruit. It prints a message like “Current fruit: apple” for each fruit in the array.
  • done: This keyword marks the end of the loop body. It tells the script that the loop has finished.

for loop

12) Write a shell script that calculates the sum of integers from 1 to N using a loop.

#!/bin/bash echo “Enter a number (N):” read N sum=0 for (( i=1; i<=$N; i++ )); do sum=$((sum + i)) done echo “Sum of integers from 1 to $N is: $sum”

Explanation: The script starts by asking you to enter a number (N) using read. This number will determine how many times the loop runs.

  • The variable sum is initialized to 0. This variable will keep track of the sum of integers.
  • The for loop begins with for (( i=1; i<=$N; i++ )). This loop structure is used to repeat a set of actions a certain number of times, in this case, from 1 to the value of N.
  • i=1 sets the loop variable i to 1 at the beginning of each iteration.
  • The loop condition i<=$N checks if i is still less than or equal to the given number N.
  • If the condition is true, the loop body executes.
  • sum=$((sum + i)) calculates the new value of sum by adding the current value of i to it. This adds up the integers from 1 to the current i value.
  • After each iteration, i++ increments the value of i by 1.
  • The loop continues running until the condition i<=$N becomes false (when i becomes greater than N).
  • Once the loop finishes, the script displays the sum of the integers from 1 to the entered number N.

439

13) Create a script that searches for a specific word in a file and counts its occurrences.

Create a script name `word_count.sh`

#!/bin/bash echo “Enter the word to search for:” read target_word echo “Enter the filename:” read filename count=$(grep -o -w “$target_word” “$filename” | wc -l) echo “The word ‘$target_word’ appears $count times in ‘$filename’.”
  • echo “Enter the word to search for:”: This line displays a message asking the user to enter a word they want to search for in a file.
  • read target_word: This line reads the input provided by the user and stores it in a variable named target_word.
  • echo “Enter the filename:”: This line displays a message asking the user to enter the name of the file they want to search in.
  • read filename: This line reads the input provided by the user and stores it in a variable named filename.
  • grep -o -w “$target_word” “$filename”: This part of the command searches for occurrences of the target_word in the specified filename. The options -o and -w ensure that only whole word matches are counted.
  • |: This is a pipe, which takes the output of the previous command and sends it as input to the next command.
  • wc -l: This part of the command uses the wc command to count the number of lines in the input. The option -l specifically counts the lines.
  • The entire command calculates the count of occurrences of the target_word in the file and assigns that count to the variable coun

441

14) Explain the differences between standard output (stdout) and standard error (stderr).

The main difference between standard output (stdout) and standard error (stderr) is as follows:

  • Standard Output (stdout): This is the default output stream where a command’s regular output goes. It’s displayed on the terminal by default. You can redirect it to a file using >.
  • Standard Error (stderr): This is the output stream for error messages and warnings. It’s displayed on the terminal by default as well. You can redirect it to a file using 2>.

15) Explain the concept of conditional statements in shell scripting.

Conditional statements in shell scripting allow us to make decisions and control the flow of our script based on certain conditions. They enable our script to execute different sets of commands depending on whether a particular condition is true or false. The primary conditional statements in shell scripting are the if statement, the elif statement (optional), and the else statement (optional).

Here’s the basic structure of a conditional statement in shell scripting:

if [ condition ]; then # Commands to execute if the condition is true elif [ another_condition ]; then # Commands to execute if another_condition is true (optional) else # Commands to execute if none of the conditions are true (optional) fi
  • [ condition ] = Command that evaluates the condition and returns a true (0) or false (non-zero) exit status.
  • then = It is a keyword which indicates that the commands following it will be executed if the condition evaluates to true.
  • elif = (short for “else if”) It is a section that allows us to specify additional conditions to check.
  • else = it is a section that contains commands that will be executed if none of the conditions are true.
  • fi = It is a keyword that marks the end of the conditional block.

16) How do you read lines from a file within a shell script?

To read lines from a file within a shell script, we can use various methods, but one common approach is to use a while loop in combination with the read command. Here’s how we can do it:

#!/bin/bash file=”/home/jayeshkumar/jayesh.txt” # Check if the file exists if [ -e “$file” ]; then while IFS= read -r line; do echo “Line read: $line” # Add your processing logic here done < “$file” else echo “File not found: $file” fi
  • file=”/home/jayeshkumar/jayesh.txt”: This line defines the variable file and assigns the full path to the file jayesh.txt in the /home/jayeshkumar directory. Change this path to match the actual path of the file you want to read.
  • if [ -e “$file” ]; then: This line starts an if statement. It checks if the file specified by the variable $file exists. The -e flag checks for file existence.
  • IFS=: The IFS (Internal Field Separator) is set to an empty value to preserve leading and trailing spaces.
  • read -r line: This reads the current line from the file and stores it in the variable line.
  • echo “Line read: $line”: This line prints the content of the line that was read from the file. The variable $line contains the current line’s content.
  • # Add your processing logic here: This is a placeholder comment where you can add your own logic to process each line. For example, you might analyze the line, extract information, or perform specific actions based on the content.
  • done < “$file”: This marks the end of the while loop. The < “$file” redirects the content of the file to be read by the loop.
  • else: If the file does not exist (the condition in the if statement is false), the script executes the code under the else branch.
  • echo “File not found: $file”: This line prints an error message indicating that the specified file was not found.

reading file

reading file

Here , we used ` pwd ` command to get the path of current directory.

17) Write a function in a shell script that calculates the factorial of a given number.

Here is the script that calculate the factorial of a given number.

#!/bin/bash # Define a function to calculate factorial calculate_factorial() { num=$1 fact=1 for ((i=1; i<=num; i++)); do fact=$((fact * i)) done echo $fact } # Prompt the user to enter a number echo “Enter a number: “ read input_num # Call the calculate_factorial function with the input number factorial_result=$(calculate_factorial $input_num) # Display the factorial result echo “Factorial of $input_num is: $factorial_result”
  • The script starts with the shebang line #!/bin/bash to specify the interpreter.
  • calculate_factorial() is defined as a function. It takes one argument, num, which is the number for which the factorial needs to be calculated.
  • Inside the function, fact is initialized to 1. This variable will store the factorial result.
  • The for loop iterates from 1 to the given number (num). In each iteration, it multiplies the current value of fact by the loop index i.
  • After the loop completes, the fact variable contains the calculated factorial.
  • The script prompts the user to enter a number using read.
  • The calculate_factorial function is called with the user-provided number, and the result is stored in the variable factorial_result.
  • Finally, the script displays the calculated factorial result.

Factorial

18) How do you handle signals like Ctrl+C in a shell script?

In a shell script, you can handle signals like Ctrl+C (also known as SIGINT) using the trap command. Ctrl+C generates a SIGINT signal when the user presses it to interrupt the running script or program. By using the trap command, you can specify actions to be taken when a particular signal is received. Here’s how you handle signals like Ctrl+C in a shell script:

#!/bin/bash cleanup() { echo “Script interrupted. Performing cleanup…” # Add your cleanup actions here exit 1 } # Set up a trap to call the cleanup function when Ctrl+C (SIGINT) is received trap cleanup SIGINT # Rest of your script echo “Running…” sleep 10 echo “Finished.”

Handling signals is important for making scripts robust and ensuring that they handle unexpected interruptions gracefully. You can customize the cleanup function to match your specific needs, like closing files, stopping processes, or logging information before the script exits.

  • #!/bin/bash: This shebang line specifies the interpreter to be used for running the script.
  • cleanup() { … }: This defines a function named cleanup. Inside this function, you can include any actions that need to be performed when the script is interrupted, such as closing files, releasing resources, or performing other cleanup tasks.
  • trap cleanup SIGINT: The trap command is used to set up a signal handler. In this case, it specifies that when the SIGINT signal (Ctrl+C) is received, the cleanup function should be executed.
  • echo “Running…”, sleep 10, echo “Finished.”: These are just sample commands to simulate the execution of a script.

446

19) Create a script that checks for and removes duplicate lines in a text file.

Here is our linux scipt in which we will remove duplicate lines from a text file.

#!/bin/bash input_file=”input.txt” output_file=”output.txt” sort “$input_file” | uniq > “$output_file” echo “Duplicate lines removed successfully.”
  • The script starts with a shebang (#!/bin/bash), which indicates that the script should be interpreted using the Bash shell.
  • The input_file variable is set to the name of the input file containing duplicate lines (change this to your actual input file name).
  • The output_file variable is set to the name of the output file where the duplicates will be removed (change this to your desired output file name).
  • The script uses the sort command to sort the lines in the input file. Sorting the lines ensures that duplicate lines are grouped together.
  • The sorted lines are then passed through the uniq command, which removes consecutive duplicate lines. The output of this process is redirected to the output file.
  • After the duplicates are removed, the script prints a success message.

duplicate line removeing

duplicate line removing

Here, we use ` cat ` to display the text inside the text file.

20) Write a script that generates a secure random password.

Here is our script to generate a secure random password.

#!/bin/bash # Function to generate a random password generate_password() { tr -dc ‘A-Za-z0-9!@#$%^&*()_+{}[]’ < /dev/urandom | fold -w 12 | head -n 1 } # Call the function and store the generated password password=$(generate_password) echo “Generated password: $password”

Note: User can accordingly change the length of there password, by replacing the number `12`.

  • The script starts with a shebang (#!/bin/bash), indicating that it should be interpreted using the Bash shell.
  • tr -dc ‘A-Za-z0-9!@#$%^&*()_+{}[]’ < /dev/urandom uses the tr command to delete (-d) characters not in the specified set of characters (A-Za-z0-9!@#$%^&*()_+{}[]) from the random data provided by /dev/urandom.
  • fold -w 12 breaks the filtered random data into lines of width 12 characters each.
  • head -n 1 selects the first line, effectively giving us a random sequence of characters of length 12.
  • The password variable is assigned the result of calling the generate_password function.
  • Finally, the generated password is displayed using echo.

448

21) Write a shell script that calculates the total size of all files in a directory.

Here is a shell script to calculate the total size of all files in a directory.

#!/bin/bash directory=”/path/to/your/directory” total_size=$(du -csh “$directory” | grep total | awk ‘{print $1}’) echo “Total size of files in $directory: $total_size”
  • The script starts with the #!/bin/bash shebang, indicating that it should be interpreted using the Bash shell.
  • The directory variable is set to the path of the directory for which you want to calculate the total file size. Replace “/path/to/your/directory” with the actual path.
  • -c: Produce a grand total.
  • -s: Display only the total size of the specified directory.
  • -h: Print sizes in a human-readable format (e.g., KB, MB, GB).
  • The output of du is piped to grep total to filter out the line that contains the total size.
  • awk ‘{print $1}’ is used to extract the first field (total size) from the line.
  • The calculated total size is stored in the total_size variable.
  • Finally, the script displays the total size using echo.

Total Size of Files

Total Size of Files

Here , we used ` pwd ` command to see the current directory path.

22) Explain the difference between if and elif statements in shell scripting.

Lets understand it by an example.

#!/bin/bash number=5 if [ $number -gt 10 ]; then echo “$number is greater than 10” else echo “$number is not greater than 10” fi echo “——–“ if [ $number -gt 10 ]; then echo “$number is greater than 10” elif [ $number -eq 10 ]; then echo “$number is equal to 10” else echo “$number is less than 10” fi

In this example, the first if block checks whether number is greater than 10. If not, it prints a message indicating that the number is not greater than 10. The second block with elif statements checks multiple conditions sequentially until one of them is true. In this case, since the value of number is 5, the output will be:

if_elif difference

if_elif difference

23) How do you use a while loop to repeatedly execute commands?

A while loop is used in shell scripting to repeatedly execute a set of commands as long as a specified condition is true. The loop continues executing the commands until the condition becomes false.

Here’s the basic syntax of a while loop:

while [ condition ]; do # Commands to be executed done
  • The `while` loop starts with the keyword `while` followed by a condition enclosed within square brackets `[ ]`.
  • The loop’s body, which contains the commands to be executed, is enclosed within the `do` and `done` keywords.
  • The loop first checks the condition. If the condition is true, the commands within the loop body are executed. After the loop body executes, the condition is checked again, and the process repeats until the condition becomes false.

Example: If we want to print numbers from 1 to 5

#!/bin/bash counter=1 while [ $counter -le 5 ]; do echo “Number: $counter” counter=$((counter + 1)) done
  • The counter variable is set to 1.
  • The while loop checks whether the value of counter is less than or equal to 5. As long as this condition is true, the loop continues executing.
  • Inside the loop, the current value of counter is printed using echo.
  • The counter is incremented by 1 using the expression $((counter + 1)).

while loop

24) Create a shell script that finds and lists all empty files in a directory.

Shell script that you can use to find and list all empty files in a directory using the `find` and `stat` commands:

#!/bin/bash directory=”$1″ if [ -z “$directory” ]; then echo “Usage: $0 <directory>” exit 1 fi if [ ! -d “$directory” ]; then echo “Error: ‘$directory’ is not a valid directory.” exit 1 fi echo “Empty files in $directory:” find “$directory” -type f -empty
  • ` #!/bin/bash `: This is called a “shebang,” and it tells the operating system to use the Bash shell to interpret and execute the script.
  • ` directory=”$1″ `: This line assigns the first command-line argument (denoted by $1) to the variable ` directory `.
  • ` if [ -z “$directory” ]; then `: This line starts an if statement that checks whether the ` directory ` variable is empty (-z tests for an empty string).
  • ` echo “Usage: $0 <directory>” `: If the directory is empty, this line prints a usage message, where ` $0 ` represents the script’s name.
  • ` exit 1 `: This line exits the script with an exit code of ` 1 `, indicating an error.
  • ` fi `: This line marks the end of the ` if ` statement.
  • ` if [ ! -d “$directory” ]; then `: This starts another if statement to check if the provided directory exists (` -d ` tests for a directory).
  • ` echo “Error: ‘$directory’ is not a valid directory.” `: If the provided directory doesn’t exist, this line prints an error message.
  • ` exit 1 `: Exits the script with an exit code of ` 1 `.
  • ` fi `: Marks the end of the second ` if` statement.
  • ` echo “Empty files in $directory:” `: If everything is valid so far, this line prints a message indicating that the script will list empty files in the specified directory.
  • ` find “$directory” -type f -empty `: This line uses the ` find ` command to search for empty files (` -empty `) of type regular files (` -type f `) in the specified directory. It then lists these empty files.

Finding empty files

Finding empty files

Note : We need to provide a directory as an argument when running the script. Here we have used the path of current directory “home/jayeshkumar/”

25) What is the purpose of the read command in shell scripting?

The read command in shell scripting lets the script ask you for information. It’s like when a computer asks you a question and waits for your answer. This is useful for scripts that need you to type something or for when the script needs to work with information from files. The read command helps the script stop and wait for what you type, and then it can use that information to do more things in the script.

Syntax of read command:

Example : If we want to take name as an input from user to print it.

#!/bin/bash echo “Please enter your name:” read name echo “Hello, $name!”

453

In summary, the read command is used to capture user input or data from files within shell scripts, making the scripts more interactive and versatile.

26) Write a shell script that converts all filenames in a directory to lowercase.

Here’s a shell script that converts all filenames in a directory to lowercase.

#!/bin/bash directory=”$1″ if [ -z “$directory” ]; then echo “Usage: $0 <directory>” exit 1 fi if [ ! -d “$directory” ]; then echo “Error: ‘$directory’ is not a valid directory.” exit 1 fi cd “$directory” || exit 1 for file in *; do if [ -f “$file” ]; then newname=$(echo “$file” | tr ‘A-Z’ ‘a-z’) [ “$file” != “$newname” ] && mv “$file” “$newname” fi done
  • #!/bin/bash : This is the shebang, specifying that the script should be interpreted using the Bash shell.
  • directory=”$1″ : This line assigns the first command-line argument to the variable directory.
  • if [ -z “$directory” ]; then : This line checks if the directory variable is empty (no argument provided when running the script).
  • echo “Usage: $0 <directory>” : If the directory is empty, this line prints a usage message with the script’s name ($0).
  • exit 1 : This line exits the script with an exit code of 1, indicating an error occurred.
  • f i: This marks the end of the first if statement.
  • if [ ! -d “$directory” ]; then : This line checks if the specified directory does not exist (-d tests for a directory).
  • echo “Error: ‘$directory’ is not a valid directory.” : If the specified directory doesn’t exist, this line prints an error message.
  • exit 1 : Exits the script with an exit code of 1.
  • fi : Marks the end of the second if statement.
  • cd “$directory” || exit 1 : Changes the current working directory to the specified directory. If the directory change fails (e.g., non-existent directory), the script exits with an error code.
  • for file in *; do: I for file in *; do: nitiates a loop that iterates over all items in the current directory (* matches all filenames).
  • if [ -f “$file” ]; then : Checks if the current loop iteration item is a regular file (-f tests for a regular file).
  • newname=$(echo “$file” | tr ‘A-Z’ ‘a-z’) : Converts the current filename ($file) to lowercase using the tr command and stores the result in the newname variable.
  • [ “$file” != “$newname” ] && mv “$file” “$newname” : Compares the original filename with the new lowercase filename. If they are different, it renames the file using the mv command.
  • fi : Marks the end of the inner if statement.
  • done : Marks the end of the loop.

454

Note : We need to provide a directory as an argument when running the script. Here we have used the path of current directory “home/jayeshkumar/test”

27) How can you use arithmetic operations within a shell script?

Arithmetic operations can be performed within a shell script using various built-in methods. The shell provides mechanisms for simple arithmetic calculations using arithmetic expansion Like:

  • Arithmetic Expansion ($((…)))
  • Using expr Command
  • Using let Command

Here is our Shell script explaning all three methods for arithmetic operations.

#!/bin/bash num1=10 num2=5 #Arithmetic Expansion ($((…))) result=$((num1 + num2)) echo “Sum: $result” #Using expr Command sum=$(expr $num1 + $num2) echo “Sum: $sum” #Using let Command let “sum = num1 + num2” echo “Sum: $sum”
  • `#!/bin/bash` : This is the shebang, specifying that the script should be interpreted using the Bash shell.
  • `num1=10` and ` num2=5` : These lines assign the values 10 and 5 to the variables ` num1 ` and ` num2 `, respectively.
  • `#Arithmetic Expansion ($((…)))` : This is a comment indicating the start of the section that demonstrates arithmetic expansion.
  • `result=$((num1 + num2))` : This line uses arithmetic expansion to calculate the sum of ` num1 ` and ` num2 ` and stores the result in the ` result ` variable.
  • `echo “Sum: $result”` : This line prints the calculated sum using the value stored in the ` result ` variable.
  • `#Using expr Command` : This is a comment indicating the start of the section that demonstrates using the ` expr ` command for arithmetic operations.
  • `sum=$(expr $num1 + $num2)` : This line uses the ` expr ` command to calculate the sum of ` num1 ` and ` num2 ` and stores the result in the ` sum ` variable. Note that the ` expr ` command requires spaces around the operators.
  • `echo “Sum: $sum”` : This line prints the calculated sum using the value stored in the ` sum ` variable.
  • `#Using let Command` : This is a comment indicating the start of the section that demonstrates using the ` let ` command for arithmetic operations.
  • `let “sum = num1 + num2″` : This line uses the ` let ` command to calculate the sum of ` num1 ` and ` num2 ` and assigns the result to the ` sum ` variable. The ` let ` command does not require spaces around the operators.

arithmetic

28) Create a script that checks if a network host is reachable.

Here’s a simple shell script that uses the ping command to check if a network host is reachable:

#!/bin/bash host=”$1″ if [ -z “$host” ]; then echo “Usage: $0 <hostname or IP>” exit 1 fi ping -c 4 “$host”   if [ $? -eq 0 ]; then echo “$host is reachable.” else echo “$host is not reachable.” fi
  • It takes a hostname or IP address as an argument and checks if the argument is provided.
  • If no argument is provided, it displays a usage message and exits.
  • It uses the ping command with the -c 4 option to send four ICMP echo requests to the specified host.
  • After the ping command runs, it checks the exit status ($?). If the exit status is 0, it means the host is reachable and the script prints a success message. Otherwise, it prints a failure message.

456

Note : We need to provide a hostname as an argument when running the script. Here we have used “google.com”

29) Write a Shell Script to Find the Greatest Element in an Array:

Here’s a shell script to find the greatest element in an array.

#!/bin/bash # Declare an array array=(3 56 24 89 67) # Initialize a variable to store the maximum value, starting with the first element max=${array[0]} # Iterate through the array for num in “${array[@]}”; do # Compare each element with the current maximum if ((num > max)); then max=$num fi done # Print the maximum value echo “The maximum element in the array is: $max”

` #!/bin/bash `: The shebang line specifies that the script should be interpreted using the Bash shell.

  • ` array=(3 56 24 89 67) `: The array is declared and initialized with values.
  • ` max=${array[0]} `: `max` is initialized with the first element of the array.
  • ` for num in “${array[@]}”; do `: A `for` loop is used to iterate through the elements of the array.
  • ` if ((num > max)); then `: An `if` statement checks if the current element `num` is greater than the current maximum `max`.
  • ` max=$num`: If`num ` is greater than `max`, `max` is updated with the value of num.
  • ` done `: The `for` loop is closed.
  • ` echo “The maximum element in the array is: $max” `: Finally, the script prints the maximum value found in the array.

461

greatest number

30) Write a scripte to calculate the sum of Elements in an Array.

#/bin/bash.

# Declare an array array=(1 65 22 19 94) # Initialize a variable to store the sum sum=0 # Iterate through the array and add each element to the sum for num in “${array[@]}”; do sum=$((sum + num)) done # Print the sum echo “The sum of elements in the array is: $sum”

` array=(1 65 22 19 94) `: The array is declared and initialized with values.

` sum=0 `: ` sum ` is initialized to zero to hold the sum of elements.

` for num in “${array[@]}”; do `: A ` for ` loop is used to iterate through the elements of the array.

` sum=$((sum + num)) `: Inside the loop, each element ` num ` is added to the ` sum ` variable.

` done `: The ` for ` loop is closed.

`echo “The sum of elements in the array is: $sum”`: Finally, the script prints the sum of all elements in the array.

462

Sum of Elements

Know More About Shell Scripts Difference between shell and kernel Difference Between Bind Shell and Reverse Shell Introduction to Linux Shell and Shell Scripting

We all geeks know that shell script is very useful to increases the work productivity as well as it save time also. So, in this article we have covered 30 very useful and most conman shell scripts examples . We hope that this complete guide on shell scripting example help you to understand the all about the shell scripts.

Similar Reads

  • Shell Script

Please Login to comment...

Improve your coding skills with practice.

 alt=

What kind of Experience do you want to share?

Previous: Bourne Shell Variables , Up: Shell Variables   [ Contents ][ Index ]

5.2 Bash Variables

These variables are set or used by Bash, but other shells do not normally treat them specially.

A few variables used by Bash are described in different chapters: variables for controlling the job control facilities (see Job Control Variables ).

($_, an underscore.) At shell startup, set to the pathname used to invoke the shell or shell script being executed as passed in the environment or argument list. Subsequently, expands to the last argument to the previous simple command executed in the foreground, after expansion. Also set to the full pathname used to invoke each command executed and placed in the environment exported to that command. When checking mail, this parameter holds the name of the mail file.

The full pathname used to execute the current instance of Bash.

A colon-separated list of enabled shell options. Each word in the list is a valid argument for the -s option to the shopt builtin command (see The Shopt Builtin ). The options appearing in BASHOPTS are those reported as ‘ on ’ by ‘ shopt ’. If this variable is in the environment when Bash starts up, each shell option in the list will be enabled before reading any startup files. This variable is readonly.

Expands to the process ID of the current Bash process. This differs from $$ under certain circumstances, such as subshells that do not require Bash to be re-initialized. Assignments to BASHPID have no effect. If BASHPID is unset, it loses its special properties, even if it is subsequently reset.

An associative array variable whose members correspond to the internal list of aliases as maintained by the alias builtin. (see Bourne Shell Builtins ). Elements added to this array appear in the alias list; however, unsetting array elements currently does not cause aliases to be removed from the alias list. If BASH_ALIASES is unset, it loses its special properties, even if it is subsequently reset.

An array variable whose values are the number of parameters in each frame of the current bash execution call stack. The number of parameters to the current subroutine (shell function or script executed with . or source ) is at the top of the stack. When a subroutine is executed, the number of parameters passed is pushed onto BASH_ARGC . The shell sets BASH_ARGC only when in extended debugging mode (see The Shopt Builtin for a description of the extdebug option to the shopt builtin). Setting extdebug after the shell has started to execute a script, or referencing this variable when extdebug is not set, may result in inconsistent values.

An array variable containing all of the parameters in the current bash execution call stack. The final parameter of the last subroutine call is at the top of the stack; the first parameter of the initial call is at the bottom. When a subroutine is executed, the parameters supplied are pushed onto BASH_ARGV . The shell sets BASH_ARGV only when in extended debugging mode (see The Shopt Builtin for a description of the extdebug option to the shopt builtin). Setting extdebug after the shell has started to execute a script, or referencing this variable when extdebug is not set, may result in inconsistent values.

When referenced, this variable expands to the name of the shell or shell script (identical to $0 ; See Special Parameters , for the description of special parameter 0). Assignment to BASH_ARGV0 causes the value assigned to also be assigned to $0 . If BASH_ARGV0 is unset, it loses its special properties, even if it is subsequently reset.

An associative array variable whose members correspond to the internal hash table of commands as maintained by the hash builtin (see Bourne Shell Builtins ). Elements added to this array appear in the hash table; however, unsetting array elements currently does not cause command names to be removed from the hash table. If BASH_CMDS is unset, it loses its special properties, even if it is subsequently reset.

The command currently being executed or about to be executed, unless the shell is executing a command as the result of a trap, in which case it is the command executing at the time of the trap. If BASH_COMMAND is unset, it loses its special properties, even if it is subsequently reset.

The value is used to set the shell’s compatibility level. See Shell Compatibility Mode , for a description of the various compatibility levels and their effects. The value may be a decimal number (e.g., 4.2) or an integer (e.g., 42) corresponding to the desired compatibility level. If BASH_COMPAT is unset or set to the empty string, the compatibility level is set to the default for the current version. If BASH_COMPAT is set to a value that is not one of the valid compatibility levels, the shell prints an error message and sets the compatibility level to the default for the current version. The valid values correspond to the compatibility levels described below (see Shell Compatibility Mode ). For example, 4.2 and 42 are valid values that correspond to the compat42 shopt option and set the compatibility level to 42. The current version is also a valid value.

If this variable is set when Bash is invoked to execute a shell script, its value is expanded and used as the name of a startup file to read before executing the script. See Bash Startup Files .

The command argument to the -c invocation option.

An array variable whose members are the line numbers in source files where each corresponding member of FUNCNAME was invoked. ${BASH_LINENO[$i]} is the line number in the source file ( ${BASH_SOURCE[$i+1]} ) where ${FUNCNAME[$i]} was called (or ${BASH_LINENO[$i-1]} if referenced within another shell function). Use LINENO to obtain the current line number.

A colon-separated list of directories in which the shell looks for dynamically loadable builtins specified by the enable command.

An array variable whose members are assigned by the ‘ =~ ’ binary operator to the [[ conditional command (see Conditional Constructs ). The element with index 0 is the portion of the string matching the entire regular expression. The element with index n is the portion of the string matching the n th parenthesized subexpression.

An array variable whose members are the source filenames where the corresponding shell function names in the FUNCNAME array variable are defined. The shell function ${FUNCNAME[$i]} is defined in the file ${BASH_SOURCE[$i]} and called from ${BASH_SOURCE[$i+1]}

Incremented by one within each subshell or subshell environment when the shell begins executing in that environment. The initial value is 0. If BASH_SUBSHELL is unset, it loses its special properties, even if it is subsequently reset.

A readonly array variable (see Arrays ) whose members hold version information for this instance of Bash. The values assigned to the array members are as follows:

The major version number (the release ).

The minor version number (the version ).

The patch level.

The build version.

The release status (e.g., beta1 ).

The value of MACHTYPE .

The version number of the current instance of Bash.

If set to an integer corresponding to a valid file descriptor, Bash will write the trace output generated when ‘ set -x ’ is enabled to that file descriptor. This allows tracing output to be separated from diagnostic and error messages. The file descriptor is closed when BASH_XTRACEFD is unset or assigned a new value. Unsetting BASH_XTRACEFD or assigning it the empty string causes the trace output to be sent to the standard error. Note that setting BASH_XTRACEFD to 2 (the standard error file descriptor) and then unsetting it will result in the standard error being closed.

Set the number of exited child status values for the shell to remember. Bash will not allow this value to be decreased below a POSIX -mandated minimum, and there is a maximum value (currently 8192) that this may not exceed. The minimum value is system-dependent.

Used by the select command to determine the terminal width when printing selection lists. Automatically set if the checkwinsize option is enabled (see The Shopt Builtin ), or in an interactive shell upon receipt of a SIGWINCH .

An index into ${COMP_WORDS} of the word containing the current cursor position. This variable is available only in shell functions invoked by the programmable completion facilities (see Programmable Completion ).

The current command line. This variable is available only in shell functions and external commands invoked by the programmable completion facilities (see Programmable Completion ).

The index of the current cursor position relative to the beginning of the current command. If the current cursor position is at the end of the current command, the value of this variable is equal to ${#COMP_LINE} . This variable is available only in shell functions and external commands invoked by the programmable completion facilities (see Programmable Completion ).

Set to an integer value corresponding to the type of completion attempted that caused a completion function to be called: TAB , for normal completion, ‘ ? ’, for listing completions after successive tabs, ‘ ! ’, for listing alternatives on partial word completion, ‘ @ ’, to list completions if the word is not unmodified, or ‘ % ’, for menu completion. This variable is available only in shell functions and external commands invoked by the programmable completion facilities (see Programmable Completion ).

The key (or final key of a key sequence) used to invoke the current completion function.

The set of characters that the Readline library treats as word separators when performing word completion. If COMP_WORDBREAKS is unset, it loses its special properties, even if it is subsequently reset.

An array variable consisting of the individual words in the current command line. The line is split into words as Readline would split it, using COMP_WORDBREAKS as described above. This variable is available only in shell functions invoked by the programmable completion facilities (see Programmable Completion ).

An array variable from which Bash reads the possible completions generated by a shell function invoked by the programmable completion facility (see Programmable Completion ). Each array element contains one possible completion.

An array variable created to hold the file descriptors for output from and input to an unnamed coprocess (see Coprocesses ).

An array variable containing the current contents of the directory stack. Directories appear in the stack in the order they are displayed by the dirs builtin. Assigning to members of this array variable may be used to modify directories already in the stack, but the pushd and popd builtins must be used to add and remove directories. Assignment to this variable will not change the current directory. If DIRSTACK is unset, it loses its special properties, even if it is subsequently reset.

If Bash finds this variable in the environment when the shell starts with value ‘ t ’, it assumes that the shell is running in an Emacs shell buffer and disables line editing.

Expanded and executed similarly to BASH_ENV (see Bash Startup Files ) when an interactive shell is invoked in POSIX Mode (see Bash POSIX Mode ).

Each time this parameter is referenced, it expands to the number of seconds since the Unix Epoch as a floating point value with micro-second granularity (see the documentation for the C library function time for the definition of Epoch). Assignments to EPOCHREALTIME are ignored. If EPOCHREALTIME is unset, it loses its special properties, even if it is subsequently reset.

Each time this parameter is referenced, it expands to the number of seconds since the Unix Epoch (see the documentation for the C library function time for the definition of Epoch). Assignments to EPOCHSECONDS are ignored. If EPOCHSECONDS is unset, it loses its special properties, even if it is subsequently reset.

The numeric effective user id of the current user. This variable is readonly.

A colon-separated list of shell patterns (see Pattern Matching ) defining the list of filenames to be ignored by command search using PATH . Files whose full pathnames match one of these patterns are not considered executable files for the purposes of completion and command execution via PATH lookup. This does not affect the behavior of the [ , test , and [[ commands. Full pathnames in the command hash table are not subject to EXECIGNORE . Use this variable to ignore shared library files that have the executable bit set, but are not executable files. The pattern matching honors the setting of the extglob shell option.

The editor used as a default by the -e option to the fc builtin command.

A colon-separated list of suffixes to ignore when performing filename completion. A filename whose suffix matches one of the entries in FIGNORE is excluded from the list of matched filenames. A sample value is ‘ .o:~ ’

An array variable containing the names of all shell functions currently in the execution call stack. The element with index 0 is the name of any currently-executing shell function. The bottom-most element (the one with the highest index) is "main" . This variable exists only when a shell function is executing. Assignments to FUNCNAME have no effect. If FUNCNAME is unset, it loses its special properties, even if it is subsequently reset.

This variable can be used with BASH_LINENO and BASH_SOURCE . Each element of FUNCNAME has corresponding elements in BASH_LINENO and BASH_SOURCE to describe the call stack. For instance, ${FUNCNAME[$i]} was called from the file ${BASH_SOURCE[$i+1]} at line number ${BASH_LINENO[$i]} . The caller builtin displays the current call stack using this information.

If set to a numeric value greater than 0, defines a maximum function nesting level. Function invocations that exceed this nesting level will cause the current command to abort.

A colon-separated list of patterns defining the set of file names to be ignored by filename expansion. If a file name matched by a filename expansion pattern also matches one of the patterns in GLOBIGNORE , it is removed from the list of matches. The pattern matching honors the setting of the extglob shell option.

An array variable containing the list of groups of which the current user is a member. Assignments to GROUPS have no effect. If GROUPS is unset, it loses its special properties, even if it is subsequently reset.

Up to three characters which control history expansion, quick substitution, and tokenization (see History Expansion ). The first character is the history expansion character, that is, the character which signifies the start of a history expansion, normally ‘ ! ’. The second character is the character which signifies ‘quick substitution’ when seen as the first character on a line, normally ‘ ^ ’. The optional third character is the character which indicates that the remainder of the line is a comment when found as the first character of a word, usually ‘ # ’. The history comment character causes history substitution to be skipped for the remaining words on the line. It does not necessarily cause the shell parser to treat the rest of the line as a comment.

The history number, or index in the history list, of the current command. Assignments to HISTCMD are ignored. If HISTCMD is unset, it loses its special properties, even if it is subsequently reset.

A colon-separated list of values controlling how commands are saved on the history list. If the list of values includes ‘ ignorespace ’, lines which begin with a space character are not saved in the history list. A value of ‘ ignoredups ’ causes lines which match the previous history entry to not be saved. A value of ‘ ignoreboth ’ is shorthand for ‘ ignorespace ’ and ‘ ignoredups ’. A value of ‘ erasedups ’ causes all previous lines matching the current line to be removed from the history list before that line is saved. Any value not in the above list is ignored. If HISTCONTROL is unset, or does not include a valid value, all lines read by the shell parser are saved on the history list, subject to the value of HISTIGNORE . The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTCONTROL .

The name of the file to which the command history is saved. The default value is ~/.bash_history .

The maximum number of lines contained in the history file. When this variable is assigned a value, the history file is truncated, if necessary, to contain no more than that number of lines by removing the oldest entries. The history file is also truncated to this size after writing it when a shell exits. If the value is 0, the history file is truncated to zero size. Non-numeric values and numeric values less than zero inhibit truncation. The shell sets the default value to the value of HISTSIZE after reading any startup files.

A colon-separated list of patterns used to decide which command lines should be saved on the history list. Each pattern is anchored at the beginning of the line and must match the complete line (no implicit ‘ * ’ is appended). Each pattern is tested against the line after the checks specified by HISTCONTROL are applied. In addition to the normal shell pattern matching characters, ‘ & ’ matches the previous history line. ‘ & ’ may be escaped using a backslash; the backslash is removed before attempting a match. The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTIGNORE . The pattern matching honors the setting of the extglob shell option.

HISTIGNORE subsumes the function of HISTCONTROL . A pattern of ‘ & ’ is identical to ignoredups , and a pattern of ‘ [ ]* ’ is identical to ignorespace . Combining these two patterns, separating them with a colon, provides the functionality of ignoreboth .

The maximum number of commands to remember on the history list. If the value is 0, commands are not saved in the history list. Numeric values less than zero result in every command being saved on the history list (there is no limit). The shell sets the default value to 500 after reading any startup files.

If this variable is set and not null, its value is used as a format string for strftime to print the time stamp associated with each history entry displayed by the history builtin. If this variable is set, time stamps are written to the history file so they may be preserved across shell sessions. This uses the history comment character to distinguish timestamps from other history lines.

Contains the name of a file in the same format as /etc/hosts that should be read when the shell needs to complete a hostname. The list of possible hostname completions may be changed while the shell is running; the next time hostname completion is attempted after the value is changed, Bash adds the contents of the new file to the existing list. If HOSTFILE is set, but has no value, or does not name a readable file, Bash attempts to read /etc/hosts to obtain the list of possible hostname completions. When HOSTFILE is unset, the hostname list is cleared.

The name of the current host.

A string describing the machine Bash is running on.

Controls the action of the shell on receipt of an EOF character as the sole input. If set, the value denotes the number of consecutive EOF characters that can be read as the first character on an input line before the shell will exit. If the variable exists but does not have a numeric value, or has no value, then the default is 10. If the variable does not exist, then EOF signifies the end of input to the shell. This is only in effect for interactive shells.

The name of the Readline initialization file, overriding the default of ~/.inputrc .

If Bash finds this variable in the environment when the shell starts, it assumes that the shell is running in an Emacs shell buffer and may disable line editing depending on the value of TERM .

Used to determine the locale category for any category not specifically selected with a variable starting with LC_ .

This variable overrides the value of LANG and any other LC_ variable specifying a locale category.

This variable determines the collation order used when sorting the results of filename expansion, and determines the behavior of range expressions, equivalence classes, and collating sequences within filename expansion and pattern matching (see Filename Expansion ).

This variable determines the interpretation of characters and the behavior of character classes within filename expansion and pattern matching (see Filename Expansion ).

This variable determines the locale used to translate double-quoted strings preceded by a ‘ $ ’ (see Locale-Specific Translation ).

This variable determines the locale category used for number formatting.

This variable determines the locale category used for data and time formatting.

The line number in the script or shell function currently executing. If LINENO is unset, it loses its special properties, even if it is subsequently reset.

Used by the select command to determine the column length for printing selection lists. Automatically set if the checkwinsize option is enabled (see The Shopt Builtin ), or in an interactive shell upon receipt of a SIGWINCH .

A string that fully describes the system type on which Bash is executing, in the standard GNU cpu-company-system format.

How often (in seconds) that the shell should check for mail in the files specified in the MAILPATH or MAIL variables. The default is 60 seconds. When it is time to check for mail, the shell does so before displaying the primary prompt. If this variable is unset, or set to a value that is not a number greater than or equal to zero, the shell disables mail checking.

An array variable created to hold the text read by the mapfile builtin when no variable name is supplied.

The previous working directory as set by the cd builtin.

If set to the value 1, Bash displays error messages generated by the getopts builtin command.

A string describing the operating system Bash is running on.

An array variable (see Arrays ) containing a list of exit status values from the processes in the most-recently-executed foreground pipeline (which may contain only a single command).

If this variable is in the environment when Bash starts, the shell enters POSIX mode (see Bash POSIX Mode ) before reading the startup files, as if the --posix invocation option had been supplied. If it is set while the shell is running, Bash enables POSIX mode, as if the command

had been executed. When the shell enters POSIX mode, it sets this variable if it was not already set.

The process ID of the shell’s parent process. This variable is readonly.

If this variable is set, and is an array, the value of each set element is interpreted as a command to execute before printing the primary prompt ( $PS1 ). If this is set but not an array variable, its value is used as a command to execute instead.

If set to a number greater than zero, the value is used as the number of trailing directory components to retain when expanding the \w and \W prompt string escapes (see Controlling the Prompt ). Characters removed are replaced with an ellipsis.

The value of this parameter is expanded like PS1 and displayed by interactive shells after reading a command and before the command is executed.

The value of this variable is used as the prompt for the select command. If this variable is not set, the select command prompts with ‘ #? ’

The value of this parameter is expanded like PS1 and the expanded value is the prompt printed before the command line is echoed when the -x option is set (see The Set Builtin ). The first character of the expanded value is replicated multiple times, as necessary, to indicate multiple levels of indirection. The default is ‘ + ’.

The current working directory as set by the cd builtin.

Each time this parameter is referenced, it expands to a random integer between 0 and 32767. Assigning a value to this variable seeds the random number generator. If RANDOM is unset, it loses its special properties, even if it is subsequently reset.

Any numeric argument given to a Readline command that was defined using ‘ bind -x ’ (see Bash Builtin Commands when it was invoked.

The contents of the Readline line buffer, for use with ‘ bind -x ’ (see Bash Builtin Commands ).

The position of the mark (saved insertion point) in the Readline line buffer, for use with ‘ bind -x ’ (see Bash Builtin Commands ). The characters between the insertion point and the mark are often called the region .

The position of the insertion point in the Readline line buffer, for use with ‘ bind -x ’ (see Bash Builtin Commands ).

The default variable for the read builtin.

This variable expands to the number of seconds since the shell was started. Assignment to this variable resets the count to the value assigned, and the expanded value becomes the value assigned plus the number of seconds since the assignment. The number of seconds at shell invocation and the current time are always determined by querying the system clock. If SECONDS is unset, it loses its special properties, even if it is subsequently reset.

This environment variable expands to the full pathname to the shell. If it is not set when the shell starts, Bash assigns to it the full pathname of the current user’s login shell.

A colon-separated list of enabled shell options. Each word in the list is a valid argument for the -o option to the set builtin command (see The Set Builtin ). The options appearing in SHELLOPTS are those reported as ‘ on ’ by ‘ set -o ’. If this variable is in the environment when Bash starts up, each shell option in the list will be enabled before reading any startup files. This variable is readonly.

Incremented by one each time a new instance of Bash is started. This is intended to be a count of how deeply your Bash shells are nested.

This variable expands to a 32-bit pseudo-random number each time it is referenced. The random number generator is not linear on systems that support /dev/urandom or arc4random , so each returned number has no relationship to the numbers preceding it. The random number generator cannot be seeded, so assignments to this variable have no effect. If SRANDOM is unset, it loses its special properties, even if it is subsequently reset.

The value of this parameter is used as a format string specifying how the timing information for pipelines prefixed with the time reserved word should be displayed. The ‘ % ’ character introduces an escape sequence that is expanded to a time value or other information. The escape sequences and their meanings are as follows; the braces denote optional portions.

A literal ‘ % ’.

The elapsed time in seconds.

The number of CPU seconds spent in user mode.

The number of CPU seconds spent in system mode.

The CPU percentage, computed as (%U + %S) / %R.

The optional p is a digit specifying the precision, the number of fractional digits after a decimal point. A value of 0 causes no decimal point or fraction to be output. At most three places after the decimal point may be specified; values of p greater than 3 are changed to 3. If p is not specified, the value 3 is used.

The optional l specifies a longer format, including minutes, of the form MM m SS . FF s. The value of p determines whether or not the fraction is included.

If this variable is not set, Bash acts as if it had the value

If the value is null, no timing information is displayed. A trailing newline is added when the format string is displayed.

If set to a value greater than zero, TMOUT is treated as the default timeout for the read builtin (see Bash Builtin Commands ). The select command (see Conditional Constructs ) terminates if input does not arrive after TMOUT seconds when input is coming from a terminal.

In an interactive shell, the value is interpreted as the number of seconds to wait for a line of input after issuing the primary prompt. Bash terminates after waiting for that number of seconds if a complete line of input does not arrive.

If set, Bash uses its value as the name of a directory in which Bash creates temporary files for the shell’s use.

The numeric real user id of the current user. This variable is readonly.

Bash: let Statement vs. Assignment

Last updated: November 26, 2022

assignment command in shell

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode , for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

1. Overview

The built-in let command is part of the Bash and Korn shell fundamental software. Its main usage focuses on building variable assignments with basic arithmetic operations.

In this article, we describe the typical usage syntax of the command. Thereupon, we show all meaningful properties that differentiate it from the ordinary variable assignment case. Next, we proceed with a comparison with alternative commands performing similar variable assignments and mathematical operations. Along with every examined subject, in order to provide a solid understanding of the command, we highlight the compelling characteristics of the command through appropriate examples.

2. Syntax and Characteristics

The let command performs variable assignments combined with basic mathematical evaluations . Its typical syntax is quite straightforward in its simplest form:

where statement1 [statement2 […]], represent variable assignments to a number or a numeric evaluation through some mathematical operation.

Variables involved in the statements obtain local scope to the command, and their attributed values can only be fixed-width decimal integers. Any attempt to assign strings on variables leads to failure.

At last, there is a significant list of compelling properties that outline the outstanding flexibility and effectiveness of this command. A comparison against the common variable assignment operation will help us understand its potential. In the following sections, we are going to explore the basic properties through some comprehensive examples.

2.1. Multiple Statements and Variable Expansion

In a single command, multiple statements can handily concatenate without the need for the semicolon punctuation ‘;’ . Normally its presence in a standard assignment expression distinguishes consequent commands staying in a single row. We can easily test this fact in the following example:

Moreover, an enhanced feature regarding the parameter expansion is that the variables’ expansion may also be referenced simply by name without making use of the familiar prefix symbol ‘$’ . Let’s see how this applies in the following case:

Finally, the drop of the prefix ‘$’ is not a restricted rule. This means that prefixed variables can still exist alone or mixed with the former type. In such a case, the presence of the variables’ expansion prefix works without conflicts:

2.2. Variables and Operations in Assignments Using Double Quotes

Additional interesting capabilities for the let command come up when assignment definitions are surrounded by double quotes.

Under a normal variable assignment instance, no spaces can exist. For both the assignment operator ‘=’ and any binary operator, it is mandatory to keep a structure with operator and operands syntactically attached. While for typical variable declarations any in-between spare spaces break the assignment:

the let command succeeds with double quotes surrounding the expressions. In this case:

As an alternative solution, multiple expressions may merge at a single double-quoted entity with subsequent statements separated with a comma ‘,’ . The latter example would appear under this prescription as follows:

2.3. Scope Visibility

Let’s see what are the characteristics of the let command’s proper environment.  The command builds a local scope for the variables acting in it. Similarly to any other local character for variables, the presence of predefined variables in this environment results in overwriting:

Furthermore, an interesting property emerges when variables are set in their local scope, but their effective value is not yet reckoned. In such a case, the value does not update when we evaluate the variable. Let’s see the details from this case in the following example:

Above, the count variable’s increment at the moment of the max assignment is still pending. So, the proper value remains still intact. By requiring the evaluation of count update before the assignment on max , the update applies in the current shell. Finally, this also does for the max variable:

2.4. Exit Status With let Command

The exit status at the end of a let command is determined by the value assigned to the rightmost variable.

Independently of the assigned value of any previous statement, the last expression is the one that defines the returned exit status. More explicitly, in the last statement, if the variable’s value corresponds to 0, the exit status returned is 1 (FALSE). In any other case, with either a positive or negative value assigned, the exit status returned is 0 (TRUE).

Below, we can observe with a simple example how the exit status acts in each case. The retrieval of the exit status evaluation comes through the variable $? :

2.5. Mathematical Operations

There is a large number of mathematical operations allowed within the assignment statements in a let command construct. Below, we list the operators with decreasing order of precedence significance. Operators residing in the same row grant the same level of precedence.

The precedence order for mathematical operators is determined by the following list (highest precedence at the top, lowest precedence at the bottom):

  • Post-increment, post-decrement ( id++ , id– )
  • Pre-increment, pre-decrement ( ++id , –id )
  • Unary minus, unary plus ( – , + )
  • Logical negation, bitwise negation ( ! , ~ )
  • Exponentiation ( ** )
  • Multiplication, division, the remainder (modulo) ( * , / , % )
  • Addition, subtraction ( + , – )
  • Bitwise shifts ( << , >> )
  • Numeric comparison ( < , > , <= , >= )
  • Equality, Inequality ( == , != )
  • AND (Bitwise & )
  • XOR (Bitwise ^ )
  • OR (Bitwise  | )
  • Logical AND ( && )
  • Logical OR ( || )
  • Ternary operator ( <Condition> ? <Statement-Condition-True> : <Statement-Condition-False> )
  • Assignments ( = , *= , /= , %= , += , -= , <<= , >>= , &= , ^= , |= )
  • Expression list operator ( <Statement> , <Statement> )

Having expressions with multiple operators, a suitable aggregation of these with parentheses can alter the default execution precedence order. With statements inside parentheses, the operators’ evaluation can execute with advanced order according to a reasonable chosen structure. This way, the type of reordering may override the standard operations’ evaluation precedence as described in the above listing.

In conclusion, with insight into the numeric representation, a numeric expression starting with 0 natively represents an octal number. Furthermore, a leading 0x or 0X character denotes a hexadecimal number. A number can similarly apply to a different arithmetic base number in the range 2-64, making use of the prefix base# . Whenever this prefix is absent, we use by default the standard base 10.

3. Alternative Options to the let Command

The let command provides particular features and enhanced capabilities related to variable assignments and mathematical operations. However, this doesn’t mean that the standard variable assignment approach is ineligible for similar tasks.

With regard to the evaluation of arithmetic operations, the arithmetic evaluation (( )) and arithmetic expansion $(( )) constructs perform an equivalent work . Their difference mainly lies in the direct or indirect sense of assignment. We illustrate this fact with the next simple examples:

Generally, we can’t use spaces around the assignment and binary operators. But with the let command, we gain the advantage of such convenience by turning on the integer attribute. In the following examples, we can follow how this practically works. For instance, using the remainder operator ‘%’ and the logical bit shifting operator ‘<<‘:

In this characteristic case, the variables customVar1 and customVar2 assume integer values through the built-in command declare . This command yields the capability of performing arithmetic operations in a let -command flavor.

Alternatively, a similar command capable of evaluating arithmetic expressions is the command expr . Still, this can comparably perform arithmetic operations, but with the cost of slightly peculiar syntax rules. Let’s inspect these specific properties below.

At first, arithmetic operators must be surrounded by space(s):

In addition, specific operators such as the multiplication (*) and the division (/) operators must have as a prefix the escape character ‘\’. For instance:

Furthermore, number comparison operators need to be used with double quotes:

Finally, operations with variable expansion occur in the usual mode:

4. Main Differences With the Standard Assignment Case

The let command structure has been implemented with various distinct features that differentiate it from the common assignment operation. Below, we highlight the most significant differences between the two cases:

  • Reference of variables without the use of the evaluation parameter expansion prefix symbol ‘$’
  • Use of multiple assignments in a single statement (double-quoted syntax type)
  • A null value evaluates to 0
  • Possibility of arbitrary use of spaces around assignment operator ‘=’ or any binary operators (double-quoted syntax type)
  • Local scope environment
  • Specific exit code return value depending on the rightmost assigned value
  • Possibility of performing arithmetic operations as exponentiation, the r emainder calculation (modulo), and logical operations (OR, AND, XOR, bit-shifting, and number reversing)

5. Conclusion

In the current article, we explored the most significant characteristics of the let command. We performed a detailed inspection of the command typology. In addition, we demonstrated its properties and features through examples for all mentioned subjects.

Proceeding, a comparison is made with the standard corresponding constructs regarding variable assignments and arithmetic operations. In conclusion, we emphasized alternative competitive operators for performing arithmetic evaluations.

IMAGES

  1. Lab Assignment- Shell Command

    assignment command in shell

  2. Solved In this assignment, your shell script will input two

    assignment command in shell

  3. Bash Assign Output of Shell Command To Variable

    assignment command in shell

  4. assigning values to variables in shell script

    assignment command in shell

  5. assigning values to variables in shell script

    assignment command in shell

  6. Learn How to Use Awk Variables, Numeric Expressions and Assignment

    assignment command in shell

VIDEO

  1. CSC 109 Shell Script Assignment Demo

  2. Run Python Files From Terminal or Command Prompt Assignment 1

  3. 4th assignment linux command

  4. CS50 final project

  5. Using Command Shell in a browser

  6. && and || Linux Bash command chaining operators

COMMENTS

  1. How to Assign Variable in Bash Script? [8 Practical Cases]

    The let command sums 5 and 3, then stores the return value to the num variable. The num variable displays the output 8 as "The value stored in num1 variable is = 8" Case 08: Assigning Shell Command Output to a Variable. Lastly, you can assign the output of a shell command to a variable using command substitution.

  2. How can I assign the output of a command to a shell variable?

    A shell assignment is a single word, with no space after the equal sign. So what you wrote assigns an empty value to thefile; furthermore, since the assignment is grouped with a command, it makes thefile an environment variable and the assignment is local to that particular command, i.e. only the call to ls sees the assigned value.. You want to capture the output of a command, so you need to ...

  3. shell

    or to obtain system start time and current shell start time, both as UNIX EPOCH, I could do two nested forks: myStarted=$(date -d "$(ps ho lstart 1)" +%s) mySessStart=$(date -d "$(ps ho lstart $$)" +%s) This work fine, but running many forks is heavy and slow. And commands like date and bc could make many operations, line by line!! See:

  4. Assign values to shell variables

    Assign values to shell variables. Creating and setting variables within a script is fairly simple. Use the following syntax: someValue is assigned to given varName and someValue must be on right side of = (equal) sign. If someValue is not given, the variable is assigned the null string.

  5. Bash Assign Output of Shell Command To Variable

    You learned how to assign output of a Linux and Unix command to a bash shell variable. For more information see GNU bash command man page here and read the following docs: Command substitution - from the Linux shell scripting tutorial wiki. See man pages using the help/man command: $ man bash $ help printf $ help echo $ man 1 printf; đŸ„ș Was ...

  6. Command-line variable assignment and command execution

    The environment for any simple command or function may be augmented temporarily by prefixing it with parameter assignments, as described above in PARAMETERS. These assignment statements affect only the envi‐ ronment seen by that command. It's also described in detail in the manual: 3.7.1 Simple Command Expansion

  7. Linux Bash: Multiple Variable Assignment

    In other words, if we can somehow use the multiple variable assignment technique, we merely need to execute the date command once to assign the seven variables, ... Unfortunately, not all programming languages support the multiple variable assignment feature. Bash and shell script don't support this feature.

  8. Assigning a command to variable

    The line you wrote defines a variable whose value is the string ls -f | grep -v /.When you use it unquoted, it expands to a list of words (the string is split at whitespace): ls, -f, |, grep, -v, /.The | character isn't special since the shell is splitting the string, not parsing it, so it becomes the second argument to the ls command.. You can't stuff a command into a string like this.

  9. 4.2. Variable Assignment

    Variable Assignment. the assignment operator (no space before and after) Do not confuse this with = and -eq, which test, rather than assign! Note that = can be either an assignment or a test operator, depending on context. Example 4-2. Plain Variable Assignment. #!/bin/bash. # Naked variables. echo.

  10. How to Work with Variables in Bash

    Here, we'll create five variables. The format is to type the name, the equals sign =, and the value. Note there isn't a space before or after the equals sign. Giving a variable a value is often referred to as assigning a value to the variable. We'll create four string variables and one numeric variable, my_name=Dave.

  11. How To Assign Output of a Linux Command to a Variable

    To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR. variable_name='command'. variable_name='command [option ...] arg1 arg2 ...'. Below are a few examples of using command substitution.

  12. 30+ Common Linux Shell Script Examples

    In computer programming, a script is defined as a sequence of instructions that is executed by another program. A shell is a command-line interpreter of Linux which provides an interface between the user and the kernel system and executes a sequence of instructions called commands. A shell is capable of running a script. A script that is passed to

  13. How do I assign the output of a command into an array?

    To assign the output of a command to an array, you need to use a command substitution inside of an array assignment. For a general command command this looks like: arr=( $(command) ) In the example of the OP, this would read: arr=($(grep -n "search term" file.txt | sed 's/:.*//')) The inner $() runs the command while the outer causes the output ...

  14. Bash Variables (Bash Reference Manual)

    The command currently being executed or about to be executed, unless the shell is executing a command as the result of a trap, in which case it is the command executing at the time of the trap. ... This variable expands to the number of seconds since the shell was started. Assignment to this variable resets the count to the value assigned, and ...

  15. Bash: let Statement vs. Assignment

    The built-in let command is part of the Bash and Korn shell fundamental software. Its main usage focuses on building variable assignments with basic arithmetic operations. In this article, we describe the typical usage syntax of the command. Thereupon, we show all meaningful properties that differentiate it from the ordinary variable assignment ...

  16. shell

    Relevant information can be found on the man page provided by the BASH maintainer (last checked August 2020). Section Shell Grammar, Simple Commands states (emphasis added): A simple command is a sequence of optional variable assignments followed by blank-separated words and redirections, and terminated by a control operator.The first word specifies the command to be executed, and is passed as ...

  17. Bash interpreting a variable assignment as a command

    1st Value is. 2nd Value is. varName is varBar. varCmd is echo bar. Command is varBar=echo bar. ./testvars.sh: line 8: varBar=echo bar: command not found. 1st Value is. 2nd Value is. It looks like Bash is interpreting the whole thing as one command name (string) and not interpreting the = as an operator.

  18. How to build a conditional assignment in bash?

    91. If you want a way to define defaults in a shell script, use code like this: : ${VAR:="default"} Yes, the line begins with ':'. I use this in shell scripts so I can override variables in ENV, or use the default. This is related because this is my most common use case for that kind of logic. ;]