The Linux Code

How to Assign Output of a Linux Command to a Variable in Bash – A Complete Guide

Command substitution is a fundamental technique in Bash scripting that allows capturing the output of a Linux command into a variable for programmatic use in your script. But how exactly does it work? In this comprehensive guide, you‘ll learn the ins and outs of assigning command output to variables using substitution in Bash.

We‘ll cover:

  • Practical examples of capturing output
  • The two methods for command substitution
  • When to use each syntax
  • Best practices for effective usage
  • Common mistakes to avoid
  • Interactive tables and charts
  • Quotes from Linux experts
  • And much more!

Whether you‘re a beginner taking your first steps into Bash scripting or a seasoned pro looking to deepen your knowledge, this guide aims to provide extensive insights and actionable advice on wielding command substitution like a pro. Let‘s get started!

An Introduction to Command Substitution: Your Ticket to Bash Scripting Success

Command substitution allows you to run shell commands and use the output in your Bash scripts for automation, text processing, system administration, and more.

Some examples include:

  • Saving the current date to a variable to timestamp log files
  • Reading a configuration file into a variable to reference in your script
  • Assigning the output of ls to a variable to iterate and process files
  • Capturing the response from curl to check a website‘s status

Without command substitution, you‘d have to manually copy-paste output or redirect it to a file. This provides a clean, programmatic way to integrate shell commands into scripts.

Bash provides two methods for substitution:

  • $(command) – preferred modern syntax
  • `command` – backwards compatible classic syntax

In this guide, we‘ll explore both methods in-depth with numerous examples and actionable tips. Let‘s start with the $(command) approach.

$(command): The Modern Go-To for Command Substitution

The $(command) syntax provides a straightforward way to assign command output to a variable:

For example, to assign the output of hostname to a variable:

Now the host variable contains the hostname and can be referenced in the script:

The $(command) executes first and is replaced with the output in-place before the variable assignment happens.

Some key advantages of $(command) :

  • More readable for nested substitutions like $(grep $(patterns) file)
  • Avoids confusion with nested quotes
  • Follows familiar command syntax standard of $( )

Let‘s look at some common use cases.

Capturing System Info

$(command) is perfect for gathering system data like hostname, OS version, disk usage etc:

Having access to this information opens up many scripting possibilities!

Reading Files and Configuration

You can load files directly into variables for easy access:

This provides easy programmatic access to settings, features flags, and more.

Working with Command Output

Text processing commands like grep , awk , sed etc can be captured:

The sky‘s the limit for piping and passing output!

Website Scraping

You can even assign output from tools like curl and wget :

Web scraping can provide data for scripts to process and analyze!

Those are just a few examples – $(command) works with any shell command. Now let‘s look at the legacy syntax.

Backticks: The Classic Syntax for Command Substitution

Before $(command) , the original way to capture command output in Bash was backticks ( ` ):

For example:

Backticks perform substitution in the same way, just with different syntax.

Some cases where backticks may be preferred:

  • Backslashes don‘t need escaping inside backticks
  • Simplifies nesting complex/quoted commands
  • Clearer to parse with lots of parentheses or curly braces

Backticks have largely been replaced by $(command) in most new scripts, but you‘ll still see them used regularly in older Linux programs and systems.

Let‘s look at some examples of capturing output using backticks:

System Info

Files and configuration, text processing.

Backticks get the job done as well, just with different syntax!

Now that we‘ve covered both methods, let‘s look at when you may want to use each.

$(command) vs Backticks: When to Use Each Syntax

The $(command) and backtick syntaxes can be used interchangeably in most cases. Some guidelines on when to use each:

Prefer $(command) when:

  • Nesting command substitutions for readability
  • You need to embed quotes/special characters in your command
  • You want to avoid confusing backticks for Markdown formatting
  • Following modern best practices

Backticks ` may be better when:

  • Dealing with lots of layered parentheses, braces, brackets
  • You don‘t want to escape backslashes
  • Your commands have lots of embedded quotes
  • Backward compatibility is needed

In most cases, I would recommend using $(command) for cleaner and more readable code in new scripts. But backticks remain a viable option if they make your specific use case simpler.

The key is to pick one syntax and stick with it consistently throughout your script. Here are a few code examples contrasting the two approaches:

Task Backticks
Hostname hostname“
Date date +%F“
Word count wc -w myfile.txt“

They achieve the same result! Now let‘s look at some best practices to use command substitution effectively.

10 Best Practices for Command Substitution

Here are some tips for safely and properly assigning command output to variables:

1. Prefer $(command) for Readability

The $( ) syntax stands out more clearly for substitution.

2. Quote Special Characters

Handle spaces, globs, newlines etc by quoting output variables:

3. Use Meaningful Variable Names

such as hostname rather than just output

4. Avoid Unnecessary Subshells

Subshells via parentheses spawn new processes. Use sparingly:

5. Beware Injection Attacks

Validate untrusted input to avoid code injection.

6. Check Return Codes

Ensure commands succeed before using output:

7. Avoid Using Excessive Substitutions

This can harm readability and performance.

8. Comment Commands Being Run

Explain where output is coming from:

9. Prefer Storing Output in Variables

Instead of writing files or passing everywhere.

10. Reference Variables Correctly

Use $var not just var when using output.

Now that you know best practices, let‘s explore some common errors and how to fix them.

Debugging Mistakes and Pitfalls

When leveraging command substitution, there are some easy mistakes to make that can lead to issues:

Forgetting $ for variables

Always use $ when referencing assigned output:

Adding extra spaces

No spaces around = or syntax:

Unbalanced parentheses

Double check for even parentheses:

Using wrong syntax

Like { } instead of $( ) :

Forgetting to quote

Quote output variables to handle spaces/newlines:

Following best practices and validating syntax will help you avoid these common pitfalls.

For even more troubleshooting advice, let‘s cover some frequently asked questions.

FAQ – Common Questions About Command Substitution

Here are answers to some often asked questions about assigning command output to variables:

Q: Can I nest command substitutions?

Yes, you can nest $(command) or backticks multiple levels, but this can get hard to read quickly. Avoid over-nesting.

Q: How does this differ from piping | or redirecting > ?

Pipes and redirects send output elsewhere. Substitution assigns it to a variable.

Q: What if my command contains single or double quotes?

Use the alternate quote type or escape characters when needed.

Q: Can I execute multiple commands and store the output?

Yes, either group them in { } or use a subshell ( ) .

Q: What if I want to assign just a part of the output?

Use pipes like grep , awk , etc to filter just the part you need.

Q: Are there performance considerations?

Excessive use can create many subshells. Balance performance vs. readability.

Q: What are the error codes if a command fails?

If a command exits non-zero, substitution will return an empty string.

I hope those questions provide some helpful context! Let‘s recap what we learned in this guide.

Summary – Assign Output Like a Pro

We‘ve covered a ton of ground on capturing output in Bash! Let‘s review the key points:

  • Use $(command) or backticks for command substitution
  • $( ) is cleaner syntax while backticks handle nesting well
  • Assign output to reference later in your script
  • Capture system info, file contents, command output, and more
  • Follow best practices for correct usage without mistakes
  • Troubleshoot issues with debugging tips
  • Nest and pipe commands to manipulate output
  • Substitution is preferred over redirecting or piping everywhere
  • Quoting and validation help avoid common pitfalls

You‘re now ready to utilize substitution like a professional!

The ability to programmatically assign the output of Linux commands to variables unlocks endless scripting possibilities. Practice makes perfect – go out there, experiment with capturing all kinds of output, and see where it takes you!

You maybe like,

Related posts, 10 awesome awk command examples for text processing.

Awk is an extremely useful command line tool for processing text data in Linux and Unix systems. It allows you to extract columns, filter lines,…

20 Practical Awk Examples for Beginners

Awk is a powerful programming language for text processing and generating reports on Linux systems. With awk, you can perform filtering, transformation, and reporting on…

25 Essential Bash Commands for Beginners

The bash shell is the default command-line interface for most Linux distributions and Apple‘s macOS. Mastering basic bash commands allows you to efficiently interact with…

3 Hour Bash Tutorial

(expanded 2500+ word article goes here…)

30 Bash Loop Examples to Improve Your Coding Skills

Loops allow you to automate repetitive tasks and are an essential part of any programming language. Bash scripting is no exception. Bash supports three types…

30 Bash Script Examples for Beginners

Bash scripting is an essential skill for Linux system administrators and power users. This comprehensive guide provides over 30 bash script examples for practical tasks…

Linux Bash: Multiple Variable Assignment

Last updated: March 18, 2024

assignment command in shell

It's finally here:

>> The Road to Membership and Baeldung Pro .

Going into ads, no-ads reading , and bit about how Baeldung works if you're curious :)

We’ve started a new DevOps area on the site. If you’re interested in writing about DevOps, check out the Contribution Guidelines .

1. Overview

Assigning multiple variables in a single line of code is a handy feature in some programming languages, such as Python and PHP.

In this quick tutorial, we’ll take a closer look at how to do multiple variable assignment in Bash scripts.

2. Multiple Variable Assignment

Multiple variable assignment is also known as tuple unpacking or iterable unpacking.

It allows us to assign multiple variables at the same time in one single line of code.

Let’s take a look at a simple Python example to understand what multiple variable assignment looks like:

In the example above, we assigned three string values to three variables in one shot.

Next, let’s prove if the values are assigned to variables correctly using the  print() function:

As the output shows, the assignment works as we expect.

Using the multiple variable assignment technique in Bash scripts can make our code look compact and give us the benefit of better performance, particularly when we want to assign multiple variables by the output of expensive command execution.

For example, let’s say we want to assign seven variables – the calendar week number, year, month, day, hour, minute, and second – based on the current date. We can straightforwardly do:

These assignments work well.

However, during the seven executions of the date commands, the current time is always changing, and we could get unexpected results.

Further, we’ll execute the date command seven times. If the command were an expensive process, the multiple assignments would definitely hurt the performance.

We can tweak the output format to ask the date command to output those required fields in one single shot:

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, something like:

Unfortunately, not all programming languages support the multiple variable assignment feature. Bash and shell script don’t support this feature.  Therefore, the assignment above won’t work.

However, we can achieve our goal in some other ways.

Next, let’s figure them out.

3. Using the read Command

The read command is a powerful Bash built-in utility to read standard input (stdin) to shell variables.

It allows us to assign multiple variables at once:

We use the -r option in the example above to disable backslash escapes when it reads the values.

However, the read command reads from stdin. It’s not so convenient to be used as variable assignments in shell scripts. After all, not all variables are assigned by user inputs.

But there are some ways to redirect values to stdin. Next, let’s see how to do it.

3.1. Using Process Substitution and IO Redirection

We know that we can use “ < FILE ” to redirect FILE  to stdin. Further, process substitution can help us to make the output of a command appear like a file.

Therefore, we can combine the process substitution and the IO redirection together to feed the  read command :

Let’s test it with the previous date command and seven variables’ assignment problem:

As the output above shows, we’ve assigned seven variables in one shot using the process substitution and IO redirection trick.

3.2. Using Command Substitution and the Here-String

Alternatively, we can use the here-string to feed the stdin of the read command:

If we replace the hard-coded string with a command substitution , we can set multiple variables using a command’s output.

Let’s test with the seven variables and the date command scenario:

We’ve assigned seven variables in one shot. Also, the date command is executed only once.

Thus, the read command can help us to achieve multiple variables assignment.

3.3. Changing the Delimiter

The  read command will take the value of the IFS   variable as the delimiter.  By default, it’s whitespace.

But we know that the output of a command is not always delimited by whitespace.

Let’s change the output format of the date command:

This time, the output is delimited by the ‘@’ character and has three fields: the week number, the current date and time, and the weekday of the current date. The second field contains a space.

Now, we’re about to assign the three fields to three variables in one shot.

Obviously, it won’t work with the default delimiter. We can change the delimiter by setting the IFS  variable:

It’s worthwhile to mention that in the example above, the change to the IFS variable only affects the  read command following it.

4. Using an Array

Another way to assign multiple variables using a command’s output is to assign the command output fields to an array.

Let’s show how it works with the date command and seven variables example:

In the example, we used the Bash built-in  readarray command to read the date command’s output.

The default delimiter used by the readarray command is a newline character . But we can set space as the delimiter using the -d option.

5. Conclusion

In this article, we’ve learned what the multiple variable assignment technique is.

Further, we’ve addressed how to achieve multiple variable assignment in Bash scripts through examples, even though Bash doesn’t support this language feature.

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.

These 14 Linux Commands Helped Me Become a Better Troubleshooter

I tried switching to fedora linux, but it wasn't for me, get creative in the linux terminal with these 9 artsy commands.

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

Defining variables in Linux.

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

Using echo to display the values held in variables in a terminal window

Let's use all of our variables at once:

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

echo "$my_boost is to $me as $his_boost is to $him (c) $this_year" in a terminal window

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

my_boost=Tequila in a terminal window

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

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

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.

Correct an incorrect examples of referencing variables in a terminal window

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

drink_of-the_Year="$my_boost $this_year" in a terminal window

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

chmod +x fcnt.sh in a terminal window

Type the following to run the script:

./fcnt.sh in a terminal window

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

chmod +x fcnt2.sh in a terminal window

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

./fnct2.sh /dev in a terminal window

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

fig13 in a terminal window

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

./special.sh alpha bravo charlie 56 2048 Thursday in a terminal window

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:

env | less in a terminal window

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

List of environment variables in less in a terminal window

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

chmod +x script_one.sh in a terminal window

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

./script_one.sh

./script_one.sh in a terminal window

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

site_name=How-To Geek in a terminal window

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"

site_name="How-To Geek" in a terminal window

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 Commands

Files

Processes

Networking

  • Linux & macOS Terminal

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.

Linux Tutorials – Learn Linux Configuration

Bash Script: Set variable example

If you are writing a Bash script and have some information that may change during the execution of the script, or that normally changes during subsequent executions, then this should be set as a variable. Setting a variable in a Bash script allows you to recall that information later in the script, or change it as needed. In the case of integers, you can increment or decrement variables, which is useful for counting loops and other scenarios.

In this tutorial, you will learn how to set variables and use them in a Bash script on a Linux system . Check some of the examples below to see how variables works.

In this tutorial you will learn:

  • How to set a variable in a Bash script
  • How to use a previously set variable
  • How to use a variable inside of another variable

How to set a variable in a Bash script

Software Requirements and Linux Command Line Conventions
Category Requirements, Conventions or Software Version Used
System Any
Software Bash shell (installed by default)
Other Privileged access to your Linux system as root or via the command.
Conventions – requires given to be executed with root privileges either directly as a root user or by use of command
– requires given to be executed as a regular non-privileged user

How to set variable in Bash script

First, let’s go over how setting a variable is done in a Bash script. This will familiarize you with the syntax so you can easily interpret the coming examples, and eventually write your own from scratch.

Executing the script gives us this output:

This is the probably the most basic example of a variable as possible, but it gets the point across. Let’s go over what is happening here:

  • The name of the variable in this example is simply var .
  • The variable is declared by using an equal sign = .
  • The variable is set to "Hello World" . The quotes are necessary in this case because of the space.
  • In order to call the variable later in the script, we precede it with a dollar sign $ .

Next, look at the examples below to see more practical examples of setting a variable in a Bash script.

Bash Script: Set variable examples

Check out the examples below to see how to set variables within a Bash script.

Here is the result from executing the script:

The lesson to take away from this example is that you can re-use a variable inside of a Bash script.

The lesson to take away from this example is that variables are very useful when reading data from the user, whether they specify that data as flags or as a response to a prompt. There is another lesson here too. Notice that when declaring the $number variable, we use the $directory variable as well. In other words, a variable inside of a variable.

Closing Thoughts

In this tutorial, you learned how to set variables and use them in Bash scripting on a Linux system. As you can see from the examples, using variables is incredibly useful and will be a common staple in most Bash scripts. The examples shown here are basic in order to introduce you to the concept, but it is normal for a Bash script to contain many variables.

Related Linux Tutorials:

  • Mastering Bash Script Loops
  • Nested Loops in Bash Scripts
  • Bash Scripting: Mastering Arithmetic Operations
  • An Introduction to Linux Automation, Tools and Techniques
  • Mastering String Concatenation in Bash Scripting
  • Customizing and Utilizing History in the Shell
  • String Concatenation in Bash Loops
  • Ansible loops examples and introduction
  • Bash Scripting: Operators
  • Things to do after installing Ubuntu 22.04 Jammy…

Linux Forum

TecAdmin

Bash Assignment Operators (Shell Scripting)

In bash programming, assignment operators are like tools that let you give values to things. For example, you can tell the computer that “x equals 5” or “name equals tecadmin” . This way, whenever you talk about “x” or “name” later in your code, the computer knows exactly what you mean. It’s like labeling boxes in a storeroom so you know what’s inside each one without opening them.

In this article, we have split the assignment operator into four basic types. Let’s go over each type one by one with an example to make it easier to understand.

1. Standard Assignment Operator

In Bash programming, the standard assignment operator is the = symbol. It is used to assign the value on the right-hand side to the variable on the left-hand side. Make sure there are no spaces around the `=` operator.

Here is an quick example:

In this example, the variable `SHELL` is assigned the value “tecadmin” . If you use `echo $DOAMIN` , the output will be “tecadmin” .

2. Compound Assignment Operators

The compound assignment operators combination of performing some operation and then assign value to variable in a single operation. Basically it reduces line of code in your script and increase performance.

Please note that Bash only supports integer arithmetic natively. If you need to perform operations with floating-point numbers, you will need to use external tools like bc.

3. Read-only Assignment Operator

The readonly operator is used to make a variable’s value constant, which means the value assigned to the variable cannot be changed later. If you try to change the value of a readonly variable, Bash will give an error.

In the above example, PI is declared as a readonly variable and assigned a value of 3.14 . When we try to reassign the value 3.1415 to PI , Bash will give an error message: bash: PI: readonly variable .

4. Local Assignment Operator

The local operator is used within functions to create a local variable – a variable that can only be accessed within the function where it was declared.

In the above example, MY_VAR is declared as a local variable in the my_func function. When we call the function, it prints “I am local” . However, when we try to echo MY_VAR outside of the function, it prints nothing because MY_VAR is not accessible outside my_func .

Assignment operators are used a lot in programming. In shell scripting, they help with saving and changing data. By learning and using these operators well, you can make your scripts work better and faster. This article talked about the basic assignment operator, compound assignment operators, and special ones like readonly and local. Knowing how and when to use each type is important for getting really good for writing Bash scripts.

Related Posts

Shell Scripting Challenge 002! Guess the Output?

Shell Scripting Challenge 002! Guess the Output?

What is the Difference Between ${} and $() in Bash

What is the Difference Between ${} and $() in Bash?

Shell Scripting Challenge - Day 1

Shell Scripting Challenge 001 | What is the output of following Script?

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

Type above and press Enter to search. Press Esc to cancel.

  • bash / FAQ / Shell Scripting

Bash variable assignment examples

by Ramakanta · Published January 19, 2013 · Updated February 11, 2015

Tutorials

This section we will describe the following: 1. Variable assignment 2. Variable substitution 3. Built-in shell variables 4. Other shell variables 5. Variable Assignment

Variable names consist of any number of letters, digits, or underscores. Upper- and lowercase letters are distinct, and names may not start with a digit.

Variables are assigned values using the = operator. There may not be any whitespace between the variable name and the value. You can make multiple assignments on the same line by separating each one with whitespace:

By convention, names for variables used or set by the shell have all uppercase letters; however, you can use uppercase names in your scripts if you use a name that isn’t special to the shell. By default, the shell treats variable values as strings, even if the value of the string is all digits. However, when a value is assigned to an integer variable (created via declare -i), Bash evaluates the righthand side of the assignment as an expression.

For example:

The += operator allows you to add or append the righthand side of the assignment to an existing value. Integer variables treat the righthand side as an expression, which is evaluated and added to the value. Arrays add the new elements to the array.

Variable Substitution

No spaces should be used in the following expressions. The colon (:) is optional; if it’s included, var must be nonnull as well as set.

var=value … Set each variable var to a value.

${var} Use value of var; braces are optional if var is separated from the following text. They are required for array variables.

${var:-value} Use var if set; otherwise, use value.

${var:=value} Use var if set; otherwise, use value and assign value to var.

${var:?value} Use var if set; otherwise, print value and exit (if not interactive). If value isn’t supplied, print the phrase parameter null or not set.

${var:+value} Use value if var is set; otherwise, use nothing.

${#var} Use the length of var.

${#*} Use the number of positional parameters.

${#@} Same as previous.

${var#pattern} Use value of var after removing text matching pattern from the left. Remove the shortest matching piece.

${var##pattern} Same as #pattern, but remove the longest matching piece.

${var%pattern} Use value of var after removing text matching pattern from the right. Remove the shortest matching piece.

${var%%pattern} Same as %pattern, but remove the longest matching piece.

${var^pattern} Convert the case of var to uppercase. The pattern is evaluated as for filename matching. If the first letter of var matches the pattern, it is converted to uppercase. var can be * or @, in which case the positional parameters are modified. var can also be an array subscripted by * or @, in which case the substitution is applied to all the elements of the array.

${var^^pattern} Same as ^pattern, but apply the match to every letter in the string.

${var,pattern} Same as ^pattern, but convert matching characters to lower case. Applies only to the first character in the string.

${var,,pattern} Same as ,pattern, but apply the match to every letter in the string.

${!prefix*},${!prefix@} List of variables whose names begin with prefix.

${var:pos},${var:pos:len} Starting at position pos (0-based) in variable var, extract len characters, or extract rest of string if no len. pos and len may be arithmetic expressions.When var is * or @, the expansion is performed upon the positional parameters. If pos is zero, then $0 is included in the resulting list. Similarly, var can be an array indexed by * or @.

${var/pat/repl} Use value of var, with first match of pat replaced with repl.

${var/pat} Use value of var, with first match of pat deleted.

${var//pat/repl} Use value of var, with every match of pat replaced with repl.

${var/#pat/repl} Use value of var, with match of pat replaced with repl. Match must occur at beginning of the value.

${var/%pat/repl} Use value of var, with match of pat replaced with repl. Match must occur at end of the value.

${!var} Use value of var as name of variable whose value should be used (indirect reference).

Bash provides a special syntax that lets one variable indirectly reference another:

$ greet=”hello, world” Create initial variable

$ friendly_message=greet Aliasing variable

$ echo ${!friendly_message} Use the alias

hello, world Example:

Built-in Shell Variables

Built-in variables are automatically set by the shell and are typically used inside shell scripts. Built-in variables can make use of the variable substitution patterns shown previously. Note that the $ is not actually part of the variable name, although the variable is always referenced this way. The following are

available in any Bourne-compatible shell:

$# Number of command-line arguments.

$- Options currently in effect (supplied on command line or to set). The shell sets some options automatically.

$? Exit value of last executed command.

$$ Process number of the shell.

$! Process number of last background command.

$0 First word; that is, the command name. This will have the full pathname if it was found via a PATH search.

$n Individual arguments on command line (positional parameters).

The Bourne shell allows only nine parameters to be referenced directly (n = 1–9); Bash allows n to be greater than 9 if specified as ${n}.

$*, $@ All arguments on command line ($1 $2 …).

“$*” All arguments on command line as one string (“$1 $2…”). The values are separated by the first character in $IFS.

“$@” All arguments on command line, individually quoted (“$1” “$2” …). Bash automatically sets the following additional variables: $_ Temporary variable; initialized to pathname of script or program being executed. Later, stores the last argument of previous command. Also stores name of matching MAIL file during mail checks.

BASH The full pathname used to invoke this instance of Bash.

BASHOPTS A read-only, colon-separated list of shell options that are currently enabled. Each item in the list is a valid option for shopt -s. If this variable exists in the environment when Bash starts up, it sets the indicated options before executing any startup files.

BASHPID The process ID of the current Bash process. In some cases, this can differ from $$.

BASH_ALIASES Associative array variable. Each element holds an alias defined with the alias command. Adding an element to this array creates a new alias; removing an element removes the corresponding alias.

BASH_ARGC Array variable. Each element holds the number of arguments for the corresponding function or dot-script invocation. Set only in extended debug mode, with shopt –s extdebug. Cannot be unset.

BASH_ARGV An array variable similar to BASH_ARGC. Each element is one of the arguments passed to a function or dot-script. It functions as a stack, with values being pushed on at each call. Thus, the last element is the last argument to the most recent function or script invocation. Set only in extended debug

mode, with shopt -s extdebug. Cannot be unset.

BASH_CMDS Associative array variable. Each element refers to a command in the internal hash table maintained by the hash command. The index is the command name and the value is the full path to the command. Adding an element to this array adds a command to the hash table; removing an element removes the corresponding entry.

BASH_COMMAND The command currently executing or about to be executed. Inside a trap handler, it is the command running when the trap was invoked.

BASH_EXECUTION_STRING The string argument passed to the –c option.

BASH_LINENO Array variable, corresponding to BASH_SOURCE and FUNCNAME. For any given function number i (starting at zero), ${FUNCNAME[i]} was invoked in file ${BASH_SOURCE[i]} on line ${BASH_LINENO[i]}. The information is stored with the most recent function invocation first. Cannot be unset.

BASH_REMATCH Array variable, assigned by the =~ operator of the [[ ]] construct. Index zero is the text that matched the entire pattern. The other

indices are the text matched by parenthesized subexpressions. This variable is read-only.

BASH_SOURCE Array variable, containing source filenames. Each element corresponds to those in FUNCNAME and BASH_LINENO. Cannot be unset.

BASH_SUBSHELL This variable is incremented by one each time a subshell or subshell environment is created.

BASH_VERSINFO[0] The major version number, or release, of Bash.

BASH_VERSINFO[1] The minor version number, or version, of Bash.

BASH_VERSINFO[2] The patch level.

BASH_VERSINFO[3] The build version.

BASH_VERSINFO[4] The release status.

BASH_VERSINFO[5] The machine type; same value as in $MACHTYPE.

BASH_VERSION A string describing the version of Bash.

COMP_CWORD For programmable completion. Index into COMP_WORDS, indicating the current cursor position.

COMP_KEY For programmable completion. The key, or final key in a sequence, that caused the invocation of the current completion function.

COMP_LINE For programmable completion. The current command line.

COMP_POINT For programmable completion. The position of the cursor as a character index in $COMP_LINE.

COMP_TYPE For programmable completion. A character describing the type of programmable completion. The character is one of Tab for normal completion, ? for a completions list after two Tabs, ! for the list of alternatives on partial word completion, @ for completions if the word is modified, or % for menu completion.

COMP_WORDBREAKS For programmable completion. The characters that the readline library treats as word separators when doing word completion.

COMP_WORDS For programmable completion. Array variable containing the individual words on the command line.

COPROC Array variable that holds the file descriptors used for communicating with an unnamed coprocess.

DIRSTACK Array variable, containing the contents of the directory stack as displayed by dirs. Changing existing elements modifies the stack, but only pushd and popd can add or remove elements from the stack.

EUID Read-only variable with the numeric effective UID of the current user.

FUNCNAME Array variable, containing function names. Each element corresponds to those in BASH_SOURCE and BASH_LINENO.

GROUPS Array variable, containing the list of numeric group IDs in which the current user is a member.

HISTCMD The history number of the current command.

HOSTNAME The name of the current host.

HOSTTYPE A string that describes the host system.

LINENO Current line number within the script or function.

MACHTYPE A string that describes the host system in the GNU cpu-company-system format.

MAPFILE Default array for the mapfile and readarray commands.

OLDPWD Previous working directory (set by cd).

OPTARG Value of argument to last option processed by getopts.

OPTIND Numerical index of OPTARG.

OSTYPE A string that describes the operating system.

PIPESTATUS Array variable, containing the exit statuses of the commands in the most recent foreground pipeline.

PPID Process number of this shell’s parent.

PWD Current working directory (set by cd).

RANDOM[=n] Generate a new random number with each reference; start with integer n, if given.

READLINE_LINE For use with bind -x. The contents of the editing buffer are available in this variable.

READLINE_POINT For use with bind -x. The index in $READLINE_LINE of the insertion point.

REPLY Default reply; used by select and read.

SECONDS[=n] Number of seconds since the shell was started, or, if n is given, number of seconds since the assignment + n.

SHELLOPTS A read-only, colon-separated list of shell options (for set -o). If set in the environment at startup, Bash enables each option present in the list before reading any startup files.

SHLVL Incremented by one every time a new Bash starts up.

UID Read-only variable with the numeric real UID of the current user.

Other Shell Variables

The following variables are not automatically set by the shell, although many of them can influence the shell’s behavior. You typically use them in your .bash_profile or .profile file, where you can define them to suit your needs. Variables can be assigned values by issuing commands of the form:

This list includes the type of value expected when defining these variables:

BASH_ENV If set at startup, names a file to be processed for initialization commands. The value undergoes parameter expansion, command substitution, and arithmetic expansion before being interpreted as a filename.

BASH_XTRACEFD=n File descriptor to which Bash writes trace output (from set -x).

CDPATH=dirs Directories searched by cd; allows shortcuts in changing directories; unset by default.

COLUMNS=n Screen’s column width; used in line edit modes and select lists.

COMPREPLY=(words …) Array variable from which Bash reads the possible completions generated by a completion function.

EMACS If the value starts with t, Bash assumes it’s running in an Emacs buffer and disables line editing.

ENV=file Name of script that is executed at startup in POSIX mode or when Bash is invoked as /bin/sh; useful for storing alias and function definitions. For example, ENV=$HOME/.shellrc.

FCEDIT=file Editor used by fc command. The default is /bin/ed when Bash is in POSIX mode. Otherwise, the default is $EDITOR if set, vi if unset.

FIGNORE=patlist Colon-separated list of patterns describing the set of filenames to ignore when doing filename completion.

GLOBIGNORE=patlist Colon-separated list of patterns describing the set of filenames to ignore during pattern matching.

HISTCONTROL=list Colon-separated list of values controlling how commands are saved in the history file. Recognized values are ignoredups, ignorespace, ignoreboth, and erasedups.

HISTFILE=file File in which to store command history.

HISTFILESIZE=n Number of lines to be kept in the history file. This may be different from the number of commands.

HISTIGNORE=list A colon-separated list of patterns that must match the entire command line. Matching lines are not saved in the history file. An unescaped & in a pattern matches the previous history line.

HISTSIZE=n Number of history commands to be kept in the history file.

HISTTIMEFORMAT=string A format string for strftime(3) to use for printing timestamps along with commands from the history command. If set (even if null), Bash saves timestamps in the history file along with the commands.

HOME=dir Home directory; set by login (from /etc/passwd file).

HOSTFILE=file Name of a file in the same format as /etc/hosts that Bash should use to find hostnames for hostname completion.

IFS=’chars’ Input field separators; default is space, Tab, and newline.

IGNOREEOF=n Numeric value indicating how many successive EOF characters must be typed before Bash exits. If null or nonnumeric value, default is 10.

INPUTRC=file Initialization file for the readline library. This overrides the default value of ~/.inputrc.

LANG=locale Default value for locale; used if no LC_* variables are set.

LC_ALL=locale Current locale; overrides LANG and the other LC_* variables.

LC_COLLATE=locale Locale to use for character collation (sorting order).

LC_CTYPE=locale Locale to use for character class functions.

LC_MESSAGES=locale Locale to use for translating $”…” strings.

LC_NUMERIC=locale Locale to use for the decimal-point character.

LC_TIME=locale Locale to use for date and time formats.

LINES=n Screen’s height; used for select lists.

MAIL=file Default file to check for incoming mail; set by login.

MAILCHECK=n Number of seconds between mail checks; default is 600 (10 minutes).

MAILPATH=files One or more files, delimited by a colon, to check for incoming mail. Along with each file, you may supply an optional message that the shell prints when the file increases in size. Messages are separated from the filename by a ? character, and the default message is You have mail in $_. $_ is replaced with the name of the file. For example, you might have MAIL PATH=”$MAIL?Candygram!:/etc/motd?New Login Message” OPTERR=n When set to 1 (the default value), Bash prints error messages from the built-in getopts command.

PATH=dirlist One or more pathnames, delimited by colons, in which to search for commands to execute. The default for many systems is /bin:/usr/bin. On Solaris, the default is /usr/bin:. However, the standard startup scripts change it to /usr/bin:/usr/ucb:/etc:.

POSIXLY_CORRECT=string When set at startup or while running, Bash enters POSIX mode, disabling behavior and modifying features that conflict with the POSIX standard.

PROMPT_COMMAND=command If set, Bash executes this command each time before printing the primary prompt.

PROMPT_DIRTRIM=n Indicates how many trailing directory components to retain for the \w or \W special prompt strings. Elided components are replaced with an ellipsis.

PS1=string Primary prompt string; default is $.

PS2=string Secondary prompt (used in multiline commands); default is >.

PS3=string Prompt string in select loops; default is #?.

PS4=string Prompt string for execution trace (bash –x or set -x); default is +.

SHELL=file Name of user’s default shell (e.g., /bin/sh). Bash sets this if it’s not in the environment at startup.

TERM=string Terminal type.

TIMEFORMAT=string A format string for the output from the time keyword.

TMOUT=n If no command is typed after n seconds, exit the shell. Also affects the read command and the select loop.

TMPDIR=directory Place temporary files created and used by the shell in directory.

auto_resume=list Enables the use of simple strings for resuming stopped jobs. With a value of exact, the string must match a command name exactly. With a value of substring, it can match a substring of the command name.

histchars=chars Two or three characters that control Bash’s csh-style history expansion. The first character signals a history event, the second is the “quick substitution” character, and the third indicates the start of a comment. The default value is !^#.

In case of any ©Copyright or missing credits issue please check CopyRights page for faster resolutions.

Like the article... Share it.

  • Click to print (Opens in new window)
  • Click to email a link to a friend (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on WhatsApp (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)
  • Click to share on Telegram (Opens in new window)

CURRENTLY TRENDING...

Tags: bash variable

  • Next story  Grep Command Tutorial For Unix
  • Previous story  Bash redirect to file and screen

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed .

Sign Up For Our Free Email Newsletter    

  • 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.

Feature `if`Staiftement `elif` Statement
Purpose Explain the difference between if and elif statements in shell scripting. Provides alternative conditions to check when the initial if condition is false.
usage Used for the initial condition. Used after the initial if condition to check additional conditions.
number of Blocks Can have only one if block. Can have multiple elif blocks, but only one else block (optional).
Execution Executes the block of code associated with the if statement if the condition is true. If the condition is false, the else block (if present) is executed (optional). Checks each elif condition in order. If one elif condition is true, the corresponding block of code is executed, and the script exits the entire conditional block. If none of the elif conditions are true, the else block (if present) is executed.
Nested Structures Can be nested within other if, elif, or else blocks. Cannot be nested within another elif block, but can be used inside an if or else block.

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.

Please Login to comment...

Similar reads.

  • Shell Script
  • SUMIF in Google Sheets with formula examples
  • How to Get a Free SSL Certificate
  • Best SSL Certificates Provider in India
  • Elon Musk's xAI releases Grok-2 AI assistant
  • Content Improvement League 2024: From Good To A Great Article

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Bash's conditional operator and assignment

Can we use bash's conditional operator with assignment operators after colon?

Bash reference manual explains the arithmetic operators as follows.

  • conditional operator expr ? expr : expr
  • assignment = *= /= %= += -= <<= >>= &= ^= |=

First, this code seems to work well:

But when I use assignment operators after : , I got 'attempted assignment to non-variable' error:

Why can we use only assignment operators before colon?

  • shell-script

Gilles 'SO- stop being evil''s user avatar

  • It may be fun to perform variable assignments using the conditional operator but it'd make your code highly unreadable. I'd prefer ((a)) && b=1 || c=1 –  devnull Commented Apr 27, 2014 at 8:34
  • @devnull I think the code's readability depends most upon who reads it. Still, it may be true what you say, but I've tested ternary operators in dash, zsh, sh , and bash and they all behave the same, despite their not being specified by POSIX. Your example only works in bash and zsh as far as I know. However, this is POSIX friendly: ( : ${a?} ) && b=1 || c=1 . I also find it far easier to read than either ternary or your own example. –  mikeserv Commented Apr 27, 2014 at 13:05

3 Answers 3

Bash parses your last command as

which should make clear why it does not work. Instead you have to use

celtschk's user avatar

This is called a ternary assignment expression. Here's a bit from another answer of mine:

You see, as you say, this is a conditional assignment operation. It depends upon conditions. The syntax works like this:

I don't believe you are using this correctly.

From wikipedia :

?: is used as follows: condition ? value_if_true : value_if_false

The condition is evaluated true or false as a Boolean expression. On the basis of the evaluation of the Boolean condition, the entire expression returns value_if_true if condition is true, but value_if_false otherwise. Usually the two sub-expressions value_if_true and value_if_false must have the same type, which determines the type of the whole expression. The importance of this type-checking lies in the operator's most common use—in conditional assignment statements. In this usage it appears as an expression on the right side of an assignment statement, as follows:

variable = condition ? value_if_true : value_if_false

The ?: operator is similar to the way conditional expressions ( if-then-else constructs) work in functional programming languages, like Scheme, ML, and Haskell, since if-then-else forms an expression instead of a statement in those languages.

I think your specific problem is related to this:

As in the if-else construct only one of the expressions 'x' and 'y' are evaluated.

If you read through the above link on ternary expressions you'll see that evaluation is short-circuited so your assignment on the false side errors because 1 = true .

In any case, it doesn't matter too much because I don't think this does what you think it does.

Community's user avatar

  • As WP says, $(()) can only contain arithmetic expressions and therefore, a general ternary assignment doesn't exist in Bash. –  zakmck Commented Apr 10, 2023 at 18:49
  • @zakmck i think you should check again. try the code in the example. –  mikeserv Commented Sep 24, 2023 at 2:07
  • @mkeserv, I usually check before commenting, now your turn: Works: echo $((1==2 ? 1 : 0)). Works, but accidentally: echo $((1==1 ? 1 : NO)). Doesn't work, evaluates $NO to 0, returns 0, not 'NO': echo $((1==2 ? 1 : NO)). Error: $((1==2 ? 1 : 'NO')). Error, "A" and "B" are evaluated to 0, result is 1: echo $(("A" == "B" ? 1 : 0)). The problem is $((x ? y : z)) is valid for numerical expressions only. Bash 5.1.8(1) –  zakmck Commented Sep 24, 2023 at 15:29
  • you cant assign to a number. the assigned variable has to be the first in the list. $((no?1:2)) and of course the ternary is valid for mumericals only; its arithmetic. –  mikeserv Commented Sep 24, 2023 at 21:10
  • the point is $(( ? : )) works when returning numbers only and the OP probably wants to know if such a ternary operator exists in general (as other say, it doesn't). –  zakmck Commented Sep 25, 2023 at 21:37

Ternary operators return a value based on a test. They are not used for branching.

Here's one way to get a pseudo-ternary operator for bash (note the back-ticks):

$result=`[ < condition > ] && echo "true-result" || echo "false-result" `

$ a= $ c=`[ $a ] && echo 1 || echo 0` $ echo $c 0 $ a=5 $ c=`[ $a ] && echo 1 || echo 0` $ echo $c 1

bearvarine's user avatar

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged bash shell shell-script arithmetic ..

  • The Overflow Blog
  • Where does Postgres fit in a world of GenAI and vector databases?
  • Mobile Observability: monitoring performance through cracked screens, old...
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites

Hot Network Questions

  • Journal keeps messing with my proof
  • Stuck on Sokoban
  • Who was the "Dutch author", "Bumstone Bumstone"?
  • Use 'fold' to wrap lines at 72 column
  • Whence “uniform distribution”?
  • Dutch Public Transportation Electronic Payment Options
  • Is there a way to resist spells or abilities with an AOE coming from my teammates, or exclude certain beings from the effect?
  • Is 3 Ohm resistance value of a PCB fuse reasonable?
  • Historical U.S. political party "realignments"?
  • What is opinion?
  • Ramification at particular level of a tower of extensions of local field
  • Do I need a level shifter in between if I want to connect 3.3 V output signals to TTL-compatible inputs?
  • What's the meaning of "running us off an embankment"?
  • I am a sailor. I am planning to call my family onboard with me on the ship from the suez
  • Why is Legion helping you whilst geth are fighting you?
  • What is the difference between a "Complaint for Civil Protection Order" and a "Motion for Civil Protection Order"?
  • magnetic boots inverted
  • Do the amplitude and frequency of gravitational waves emitted by binary stars change as the stars get closer together?
  • What is the meaning of “即采即发”“边采边发”?
  • Is the spectrum of Hawking radiation identical to that of thermal radiation?
  • How can judicial independence be jeopardised by politicians' criticism?
  • Infinite suspension is cotangent complex
  • The answer is not wrong
  • Book or novel about an intelligent monolith from space that crashes into a mountain

assignment command in shell

CS 1110 Fall 2024 – Intro to Computing: Design & Development

Text-Based Commands

Python first became popular as a scripting language , which is used to automate repetitive tasks on a computer. As a scripting language, it is heavily geared toward being used in a text-based command shell . In order to learn how to get the most of out Python, you need to learn how to use your command shell.

Command shells are operating system dependent. They are called different things depending on whether you are using Windows, MacOS, or Linux. The commands that you are allowed to type in them also depend on your choice of OS. Below we describe how to use the command shell in each of the popular computer operative systems.

The specific commands on the various operating systems are similar, but they can also be very, very different (particularly between Windows and MacOS/Linux). If you have never used a command shell before, we highly recommand that you pick one operating system and use it for the entire semester . Otherwise, this can get very confusing. In particular, if you have a Macintosh laptop, we suggest that you bring it to the lab sections, as the lab computers are all Windows machines.

As with the Python installation instructions, this tutorial is very step-by-step. This is to give you a quick introduction to the command shell. But we are not expecting you to master the command shell immediately. You will get a lot of practice with it over the course of the semester.

Table of Contents

Navigating directories.

  • Manipulating Files

Getting Help

Before learning the OS specific commands, it is important to understand what all command shells have in common. A command shell is a text-based version of a file manager. So it is the equivalent of Windows Explorer on Windows, or the Finder on MacOS. At any given time it is open to a specific folder (or directory ) on your computer. We call the folder that is currently open in the shell the working directory . The pictures below show a command shell and a graphical file manager with the same working directory.

Windows PowerShell   Windows Explorer
 

From within the command shell, you can do everything that you could do with a graphical file manager. You can move, rename, and copy files. You can change the current directory. You can even run programs. In a graphical file manager, you run a program by double-clicking on it; in a command shell, you type the name of the program. We cover this in more detail in the Python tutorial .

Every computer user has what is known as a home directory . This is the folder that has your name. In Windows 10, this is a hidden folder which contains all your other folders, like Downloads or the Desktop. In MacOS, it is the folder you typically see when you ask for a new Finder window. Whenever you open a new command shell, it always starts in the home directory. As your homework and lab assignments will often be in different folders, the first thing you need to learn about the command shell is how to change directories. That is the focus of the tutorials below.

assignment command in shell

In Windows, the command shell is called the PowerShell . There is another, older command shell called the Command Prompt . However, official Microsoft policy since Windows 10 is to use the newer PowerShell, and that is what we recommend. It is much closer to the MacOS and Linux versions we show in class, and so you will be less confused.

To find the PowerShell, just search for “PowerShell” in the search box at the bottom of the Start Menu. When you start up the PowerShell, you get a Window that looks something like the illustration below. At any given time, the bottom line of the PowerShell is the working directory followed by a > symbol.

To get the PowerShell to do something, simply type in a command, and hit Return . The shell will then process the command, either doing something or printing out an error message. When done, it will present the prompt again, ready for you to type in a new command.

As we mentioned above, the PowerShell works like the Windows Explorer. At any given time it is open to a specific folder (or directory ) on your computer, which we call the working directory .

When working on a Python assignment, you want to make sure that the working directory is the directory that contains the .py files you are currently editing. Many a student has found themselves editing a .py folder while testing one (of the same name) in a different folder. You might be tempted to just put everything in your home directory. However, this is a bad idea, as the folder will get very cluttered as the semester progresses.

windows-powershell

The two most important commands to know in Windows are ls and cd . Typing in ls displays the current working directory as well as all of its contents. An example of the ls command is shown below.

windows-ls

The cd command is an abbreviation for “change directory”. It is how you move from one folder to another. When you type this command into the PowerShell, you must give it two things: the command cd and the name of the folder you wish to go to. Using the example above, suppose we wish to switch the working directory to Desktop. Then you would type

Try this out and then type ls . See the difference?

There are a couple of important tricks to know about the cd command.

Backing Out of a Directory

The simplest form cd can only move to a folder that is “sees” (e.g. is a folder inside the working directory). If you change to directory (such as Desktop), you can no longer see the original directory (your home directory); it is outside of the current working directory. So how do you back-out if you go into a folder by mistake?

The solution is that there is a special folder called .. . This refers to the folder that contains the current one. Type

and see what happens. If you typed it just after moving into the Desktop folder (from the previous example), then you should be back in your home directory.

Combining cd .. with regular uses of the cd command are enough to allow you to move up and down the directory hierarchy on your computer.

Tab Completion

If you are new to the PowerShell, you might find yourself quickly getting tired of all the typing that you have to do. Particularly when you have a directory with a very long name. A slight misspelling and you have to start all over again.

Fortunately, Windows has tab completion to speed things up. Go to your home directory and type ( but do not hit Return )

Now hit the tab key. See what happens? Windows turns “D” into the first folder that it can find that starts with that letter (which is likely to be Desktop, and not Documents, as it comes first alphabetically).

Changing Multiple Directories at Once

Suppose you are currently in the your home directory; you want to move to the folder “Favorites” which is inside of “Documents”. You could do this with two cd commands. But to do it with a single command, you just connect the folders with a \ , as follows:

When you combine this with .. , you can do some rather clever tricks. Suppose you are currently in the Desktop directory, and you want to move in the Documents directory (which is contained in your home directory). You can do this with the command

We refer to these expressions as paths ; they are are a “path” from the working directory to the directory that you want to go to.

Absolute Paths

The paths that we have shown you are more properly called relative paths . They show how to get from the working directory to your new directory. The correct path to use depends on exactly which directory is the current working directory.

Absolute paths are paths that do not depend on the working directory; instead they depend on the disk drive. They always start with name of the drive. For example, suppose you inserted a USB drive into the computer, and you wanted to open that drive in the PowerShell. The USB drive will (typically) be the the E: drive, so you simply type

You can combine this with the \ symbol to move anywhere you want on the USB stick. If the USB stick has a folder called “Python” on it, simply type

Any time that you need to change disk drives, you need to use absolute paths. If your user account is called “Sally”, then you return to your home directory by typing

Folder Names with Spaces

The PowerShell breaks up the commands that you type in by spaces. That means that if you have a folder with spaces in the name, it will break it up into references to two different folders. For example, suppose you have a folder called “Python Examples”, and you type

You will get an error saying that Windows cannot find that path.

To solve the problem, put the directory in quotes. The following should work correctly.

If you are changing multiple directories then you need to put the entire path in quotes (not just the folder). For example, if you want to go to “Program Files” on the C drive, type

The Drag-and-Drop Shortcut

If you do not learn anything else about the PowerShell, you should learn this one trick (which works on MacOS and most Linux systems as well). If you take a folder and drag-and-drop it onto the PowerShell, it will fill the window with the absolute pathname of that folder. Therefore, to quickly move the PowerShell to a a specific folder, do the following:

  • Type cd followed by a space.
  • Drag and drop the folder on to the PowerShell.
  • Hit Return .

windows-drag-drop

This is a very useful skill and you will see your instructor use it often in class.

Manipulating Files (OPTIONAL)

The PowerShell allows you to do everything that Windows Explorer can do (and more). You can use the PowerShell to make folders, move files, and delete files. However, none of this is necessary for you to learn. For this class, you never need to understand how to do anything other than navigate directories . You can do everything else in Windows Explorer (or some other program) if you wish.

Make a Directory

To make a new folder or directory, use the command mkdir followed by the name of the new folder. For example:

The new folder will appear in the current working directory.

You can also delete a directory with the rmdir command. For example, to delete the folder we just made, type

The PowerShell will only delete empty directories. If there is anything in a directory, it will not let you delete it. You have to delete the contents first.

Move (or Rename) a File

You move files with the move command. The way this command works is that you give it two file names. It searches for a file with the first file name; once it finds it, it makes a copy with the new file name and then deletes the original.

For example, suppose you wanted to rename the file test.py to assignment3.py . Then you would type

(this by the way, illustrates why paths cannot have spaces in them).

If the second filename is path to a file, then it will move the the file into the correct directory. For example, suppose we now wanted to move assignment3.py to the Desktop (which is a folder in the current working directory), and rename it completed.py1 . Then we would type

If we want to keep the name as assignment3.py , you could shorten this to

In this case, the PowerShell will move assignment3.py into Desktop, but keep the name of the file unchanged.

Copy a File

The move command will always delete the original (name of) the file when it is done. Sometimes we want to make a copy of a file. We do that with the copy command. Suppose that assignment3.py is in the working directory and we want to put a copy on the Desktop without deleting the original. Then we would type

Delete a File

Files are deleted with the del command. In our running example, to delete the file assignment3.py , you would type

Be very careful with this command. It completely erases the file. It does not move the file your Recycle Bin . You cannot retrieve a file deleted this way.

There are hundreds of resources out there on how to learn to use the PowerShell in Windows. If you want to learn more, we suggest this popular tutorial as a starting point.

If have are having difficulty with the PowerShell, please see one of the course staff . They are available to help.

On the Macintosh, the command shell is called the Terminal . If it is not in your Dock (where it belongs!), it can be found in the Applications > Utilities folder as shown below. We recommend putting it in your Dock immediately.

macos-applications-terminal

When you start up the Terminal, you will get some message about the “last login” (a holdover of the days in which Terminals were used to connect machines over the network) followed by a line with a cursor that looks like a box. The left side of the line will depend on your settings, but the last symbol will likely be either a $ or a >. This symbol is called the prompt, and it is a cue for you to type something into the Terminal.

To get the Terminal to do something, simply type in a command, and hit Return . The shell will then process the command, either doing something or printing out an error message. When done, it will present the prompt again, ready for you to type in a new command.

As we mentioned above, the Terminal works a lot like the Finder. At any given time it is open to a specific folder (or directory ) on your computer, which we call the working directory .

Because you often need to change your working directory, the three most important commands to know in the Terminal are pwd , ls , and cd . Typing in pwd displays the current working directory. The command ls lists the contents (files and folders) in the working directory. An example of these two commands is shown below.

macos-ls

The cd command is an abbreviation for “change directory”. It is how you move from one folder to another. When you type this command into the Terminal, you must give it two things: the command cd and the name of the folder you wish to go to. Using the example above, suppose you wish to switch the working directory to Desktop. Then you would type

It is also possible to type cd by itself, without a directory name. If you do this, it will immediately put you back in your home folder. This is very helpful should you ever get lost while using the Terminal.

If you are new to the Terminal, you might find yourself quickly getting tired of all the typing that you have to do. Particularly when you have a directory with a very long name. A slight misspelling and you have to start all over again.

Fortunately, MacOS has tab completion to speed things up. Go to your home directory and type ( but do not hit Return )

Now hit the tab key. See what happens? It completes the work “Desk” to “Desktop”, because it is the only thing in your home folder that starts with “Desk” (if you actually do have something else in your folder that starts with “Desk”, this example will not work).

As another example type (but do not hit Return)

and hit tab again. There are at least two things in your home directory that start with D: Desktop and Documents. MacOS does not know which one to complete to, so it lists the possibilities for you. Tab autocompletion only works when the Terminal has enough information to uniquely pick one option from the current folder. Try doing this again with

What happens?

Suppose you are currently in the your home directory and you want to move to the folder “iTunes” which is inside of “Music”. You could do this with two cd commands. But to do it with a single command, you just connect the folders with a / , as follows:

We refer to these expressions as paths . They are are a “path” from the working directory to the directory that you want to go to.

Absolute paths are paths that do not depend on the working directory. In MacOS (and all Unix systems), absolute paths start with a / . This / represents the root directory that contains everything else. For example, if you wanted to go to your Applications directory (which is just inside the root directory), you would type

Absolute paths are very important when you are trying to navigate to a different disk drive. In MacOS, when you plug in a new disk drive it is added to the /Volumes folder (note the / indicating that Volumes is just inside the root folder). Suppose you have a Kingston USB drive from the Campus store named KINGSTON . To view the contents of this drive in the terminal, type

To drive home the difference between relative and absolute paths, create a folder called “Applications” in your home directory. Make sure the terminal is in the home directory (go home by typing cd by itself) and type

Look at the contents with ls . Now go back to the home directory again and type

Look at the contents with ls . See the difference?

The Terminal breaks up the commands that you type in by spaces. That means that if you have a folder with spaces in the name, it will break it up into references to two different folders. For example, suppose you have a folder called “Python Examples”, and you type

You will (likely) get an error saying that the folder “Python” does not exist.

If you are changing multiple directories then you need to put the entire path in quotes (not just the folder). For example, if “Python Examples” were on the Desktop, you would type

Alternatively, you can represent a space using the escape character \ which we talked about in class. For example, the following should also work correctly:

If you use Tab Completion a lot, you will notice that this is the prefered way of handling spaces.

If you do not learn anything else about the Terminal, you should learn this one trick. If you take a folder and drag and drop it onto the Terminal, it will fill the window with the absolute pathname of that folder. Therefore, to quickly move the Terminal to a a specific folder, do the following:

  • Drag and drop the folder on to the Terminal window.

macos-drag-drop

This trick works on Windows and Linux as well. However, MacOS has an even faster trick that is unique to its operating system. Simply take the folder icon and drop it onto the Terminal icon (in your Dock), and it will open a new Terminal window with that folder as its working directory. This is a very useful skill and you will see your instructor use it often in class.

The Terminal allows you to do everything that Finder can do (and more). You can use the Terminal to make folders, move files, and delete files. However, none of this is necessary for you to learn. For this class, you never need to understand how to do anything other than navigate directories . You can do everything else in the Finder (or some other program) if you wish.

To make a new folder or directory, use the command mkdir followed by the name of the new folder. For example, type:

You can also delete a directory with the rmdir command. For example, to delete the folder you just made, type

The Terminal will only delete empty directories. If there is anything in a directory, it will not let you delete it. You have to delete the contents first.

You move files with the mv command. The way this command works is that you give it two file names. It searches for a file with the first file name; once it finds it, it makes a copy with the new file name and then deletes the original.

If the second filename is path to a file, then it will move the the file into the correct directory. For example, suppose you now wanted to move assignment3.py to the Desktop (which is a folder in the current working directory), and rename it completed.py . Then you would type

If you want to keep the name as assignment3.py , you could shorten this to

In this case, the Terminal will move assignment3.py into Desktop, but keep the name of the file unchanged.

The mv command will always delete the original (name of) the file when it is done. Sometimes you want to make a copy of a file. We do that with the cp command. Suppose that assignment3.py is in the working directory and we want to put a copy on the Desktop without deleting the original. Then you would type

Files are deleted with the rm command. In our running example, to delete the file assignment3.py , you would type

Be very careful with this command. It completely erases the file. It does not move the file your Trash . You cannot retrieve a file deleted this way.

There are many resources out there on how to learn to use the Terminal in MacOS. If you want to learn more, we suggest this popular tutorial as a starting point.

If have are having difficulty with the Terminal, please see one of the course staff . They are available to help.

Let’s be honest here. If you use Linux, do you really need to learn how to use the command shell? How is it possible to do anything in Linux without knowing how to use the command shell?

On the off chance that you honestly have never used a command shell in Linux, the hard part is finding the program that provides access to the shell. Which program to use depends on your choice of GUI.

  • Gnome: Gnome Terminal
  • KDE: konsole

Once you have that running, simply refer to the instructions for MacOS . While the programs are not exactly the same (particularly if you are running a shell other than Bash ), they are close enough for purposes of this class.

If have are having difficulty with the command shell in Linux, please see one of the course staff . They are available to help.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Command not found error in Bash variable assignment

I have this script called test.sh:

when I run sh test.sh I get this:

What am I doing wrong? I look at extremely basic/beginners bash scripting tutorials online and this is how they say to declare variables... So I'm not sure what I'm doing wrong.

I'm on Ubuntu Server 9.10. And yes, bash is located at /bin/bash .

  • variable-assignment

codeforester's user avatar

  • 121 I'm glad you did ask the question, you're not the only bash noob out there! –  miller the gorilla Commented Aug 26, 2015 at 10:40
  • 11 Thanks for asking that question. This is not a question to be embarrassed about. I am working late night in office & there is no Bash expert around me to answer this. –  Adway Lele Commented Jan 19, 2016 at 16:49
  • 4 These days (almost seven years later!) there's a FOSS linter/analyzer called shellcheck that will autodetect this and other common syntax issues. It can be used online or installed offline and integrated in your editor. –  that other guy Commented Nov 8, 2016 at 17:52
  • See also stackoverflow.com/questions/26971987/… –  tripleee Commented Oct 2, 2017 at 13:36
  • I'd recommend you to use: #!/usr/bin/env bash instead of putting directly #!/bin/bash unless you're absolutely sure your bash is in /bin because of this answer: stackoverflow.com/a/21613044/3589567 –  wchmb Commented Feb 21, 2018 at 10:58

6 Answers 6

You cannot have spaces around the = sign.

When you write:

bash tries to run a command named STR with 2 arguments (the strings = and foo )

bash tries to run a command named STR with 1 argument (the string =foo )

bash tries to run the command foo with STR set to the empty string in its environment.

I'm not sure if this helps to clarify or if it is mere obfuscation, but note that:

  • the first command is exactly equivalent to: STR "=" "foo" ,
  • the second is the same as STR "=foo" ,
  • and the last is equivalent to STR="" foo .

The relevant section of the sh language spec, section 2.9.1 states:

A "simple command" is a sequence of optional variable assignments and redirections, in any sequence, optionally followed by words and redirections, terminated by a control operator.

In that context, a word is the command that bash is going to run. Any string containing = (in any position other than at the beginning of the string) which is not a redirection and in which the portion of the string before the = is a valid variable name is a variable assignment, while any string that is not a redirection or a variable assignment is a command. In STR = "foo" , STR is not a variable assignment.

William Pursell's user avatar

  • 11 If you have a variable with a name that contaings "-", the same error happens. In that case, the solution is to remove the "-" –  chomp Commented Jun 17, 2016 at 2:27
  • 3 chomp@ In rule 7b of section 2.10.10 of pubs.opengroup.org/onlinepubs/9699919799 "If all the characters preceding '=' form a valid name (see XBD Name), the token ASSIGNMENT_WORD shall be returned." Following the link to section 3.231 of pubs.opengroup.org/onlinepubs/9699919799 , we find "In the shell command language, a word consisting solely of underscores, digits, and alphabetics from the portable character set. The first character of a name is not a digit.". So the word FOO-BAR=qux is not a variable assignment since FOO-BAR is not a valid name. –  William Pursell Commented Jun 17, 2016 at 13:30
  • 2 I am offering a bounty to reward this clear explanation to an always common issue for beginners (well, and also to be able to find it faster whenever I want to link it :D). Thanks for making things this easy! –  fedorqui Commented Aug 16, 2016 at 11:54
  • 1 @fedorqui Thanks! I'm not entirely convinced that this is a clear explanation, and I often wonder if it could be made simpler. –  William Pursell Commented Aug 16, 2016 at 21:29
  • 2 @Timo $st=$i is not a variable assignment. It expands to a string, and that string is executed as a command. It seems like you are trying to do eval $st=$i . Don't do that. –  William Pursell Commented Nov 9, 2020 at 17:05

Drop the spaces around the = sign:

Joey's user avatar

  • 11 This is funny, though, as set foo = bar is a common mistake in Windows batch files as well—and there the batch language is ridiculed for it ;-) –  Joey Commented Feb 15, 2010 at 18:36
  • Thanks @joey. I was stuck in writing a shell script where i was initializing variables with spaces after "=". You saved my day –  Lalit Rao Commented Oct 2, 2015 at 13:10
  • Why bash doesn't accept numbers in the left field? like 3="Hello World", it complains about command not found –  Freedo Commented Jan 19, 2018 at 16:51
  • in a while, fails for me: eval $tag_found=0 –  Kiquenet Commented Aug 14 at 8:29

In the interactive mode everything looks fine:

Obviously(!) as Johannes said, no space around = . In case there is any space around = then in the interactive mode it gives errors as

No command 'str' found

Benjamin W.'s user avatar

  • 3 But note the OP was saying STR = "Hello World" , so this answer does not apply here. –  fedorqui Commented Aug 16, 2016 at 12:05
  • @Arkapravo what is the meaning of the interactive mode, is it has something to do with the $ mark –  Kasun Siyambalapitiya Commented Nov 22, 2016 at 13:24
  • @KasunSiyambalapitiya by "interactive mode" he means typing those commands in the actual terminal, not into a script. –  numbermaniac Commented Jan 5, 2017 at 23:59

I know this has been answered with a very high-quality answer. But, in short, you cant have spaces.

Didn't work because of the spaces around the equal sign. If you were to run...

It would work

Derek Haber's user avatar

When you define any variable then you do not have to put in any extra spaces.

So remove spaces:

and it will work fine.

Knowledge Cube's user avatar

To add to the accepted answer - using dashes in your variable name will give the same error. Remove - to get rid of the error.

Zhenya's user avatar

Not the answer you're looking for? Browse other questions tagged bash shell syntax sh variable-assignment or ask your own question .

  • The Overflow Blog
  • Where does Postgres fit in a world of GenAI and vector databases?
  • Mobile Observability: monitoring performance through cracked screens, old...
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Staging Ground Reviewer Motivation
  • Feedback requested: How do you use tag hover descriptions for curating and do...

Hot Network Questions

  • How to reply to reviewers who ask for more work by responding that the paper is complete as it stands?
  • Why are complex coordinates outlawed in physics?
  • How does the summoned monster know who is my enemy?
  • I would like to add 9 months onto a field table that is a date and have it populate with the forecast date 9 months later
  • Which hash algorithms support binary input of arbitrary bit length?
  • Why is the movie titled "Sweet Smell of Success"?
  • Why did the Fallschirmjäger have such terrible parachutes?
  • AM-GM inequality (but equality cannot be attained)
  • What is the highest apogee of a satellite in Earth orbit?
  • magnetic boots inverted
  • What is the meaning of “即采即发”“边采边发”?
  • What does "seeing from one end of the world to the other" mean?
  • What is opinion?
  • What's the meaning of "running us off an embankment"?
  • How did Oswald Mosley escape treason charges?
  • Trying to install MediaInfo Python 3.13 (Ubuntu) and it is not working out as expected
  • Is the spectrum of Hawking radiation identical to that of thermal radiation?
  • Ramification at particular level of a tower of extensions of local field
  • Background for the Elkies-Klagsbrun curve of rank 29
  • Is there a difference between these two layouts?
  • Does Vexing Bauble counter taxed 0 mana spells?
  • Rings demanding identity in the categorical context
  • Book or novel about an intelligent monolith from space that crashes into a mountain
  • I am a sailor. I am planning to call my family onboard with me on the ship from the suez

assignment command in shell

COMMENTS

  1. 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 ...

  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. ← Variables • Home • Default shell variables value →. Creating and setting variables within a script is fairly simple. Use the following syntax: varName= someValue. someValue is assigned to given varName and someValue must be on right side of = (equal) sign. If someValue is not given, the variable is ...

  5. How to Assign Output of a Linux Command to a Variable in Bash

    The $(command) syntax provides a straightforward way to assign command output to a variable: output=$(command) For example, to assign the output of hostname to a ... Those are just a few examples - $(command) works with any shell command. Now let's look at the legacy syntax. Backticks: The Classic Syntax for Command Substitution. Before ...

  6. Linux Bash: Multiple Variable Assignment

    It's not so convenient to be used as variable assignments in shell scripts. After all, not all variables are assigned by user inputs. But there are some ways to redirect values to stdin. Next, let's see how to do it. ... Another way to assign multiple variables using a command's output is to assign the command output fields to an array.

  7. 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.

  8. 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.

  9. Bash Script: Set variable example

    If you are writing a Bash script and have some information that may change during the execution of the script, or that normally changes during subsequent executions, then this should be set as a variable. Setting a variable in a Bash script allows you to recall that information later in the script, or change it as needed. In the case of integers, you can increment or decrement variables, which ...

  10. 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.

  11. shell

    With GNU Make, you can use shell and eval to store, run, and assign output from arbitrary command line invocations. The difference between the example below and those which use := is the := assignment happens once (when it is encountered) and for all. Recursively expanded variables set with = are a bit more "lazy"; references to other variables remain until the variable itself is referenced ...

  12. shell

    About your code: Apart from using set to try to set a variable (this has been pointed out by Kamil Maciorowski already, and that is how it's done in the csh and tcsh shells), your output could be simplified by grouping some commands together, especially the ones inside the loop. The touch is also not needed as redirecting into a non-existing file creates it.

  13. 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

  14. Bash Assignment Operators (Shell Scripting)

    Assignment operators are used a lot in programming. In shell scripting, they help with saving and changing data. By learning and using these operators well, you can make your scripts work better and faster. This article talked about the basic assignment operator, compound assignment operators, and special ones like readonly and local.

  15. Bash variable assignment examples

    Other shell variables 5. Variable Assignment. Variable names consist of any number of letters, digits, or underscores. Upper- and lowercase letters are distinct, and names may not start with a digit. ... available in any Bourne-compatible shell: $# Number of command-line arguments. $- Options currently in effect (supplied on command line or to ...

  16. Bash interpreting a variable assignment as a command

    Everything works except the assignment execution itself. Here's what I get: varName is varFoo. varCmd is echo foo. Command is varFoo=echo foo. ./testvars.sh: line 8: varFoo=echo foo: command not found. 1st Value is. 2nd Value is. varName is varBar.

  17. 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

  18. shell

    The importance of this type-checking lies in the operator's most common use—in conditional assignment statements. In this usage it appears as an expression on the right side of an assignment statement, as follows: variable = condition ? value_if_true : value_if_false

  19. How to build a conditional assignment in bash?

    90. 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. ;]

  20. Text-Based Commands

    Before learning the OS specific commands, it is important to understand what all command shells have in common. A command shell is a text-based version of a file manager. So it is the equivalent of Windows Explorer on Windows, or the Finder on MacOS. ... When working on a Python assignment, ...

  21. Exit code of variable assignment to command substitution in Bash

    This is not bash-specific. Quoting the end of section 2.9.1 "Simple Commands" in the "Shell & Utilities" volume of the The Open Group Base Specifications Issue 7, POSIX.1-2017 : If there is no command name, but the command contained a command substitution, the command shall complete with the exit status of the last command substitution performed

  22. shell

    A "simple command" is a sequence of optional variable assignments and redirections, in any sequence, optionally followed by words and redirections, terminated by a control operator. In that context, a word is the command that bash is going to run.