How-To Geek

How to work with variables in bash.

Want to take your Linux command-line skills to the next level? Here's everything you need to know to start working with variables.

Hannah Stryker / How-To Geek

Quick Links

Variables 101, 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

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

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=

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=

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.

The Shell Scripting Tutorial

Variables - part 1.

Just about every programming language in existence has the concept of variables - a symbolic name for a chunk of memory to which we can assign values, read and manipulate its contents. The Bourne shell is no exception, and this section introduces that idea. This is taken further in Variables - Part II which looks into variables which are set for us by the environment. Let's look back at our first Hello World example. This could be done using variables (though it's such a simple example that it doesn't really warrant it!) Note that there must be no spaces around the " = " sign: VAR=value works; VAR = value doesn't work. In the first case, the shell sees the " = " symbol and treats the command as a variable assignment. In the second case, the shell assumes that VAR must be the name of a command and tries to execute it. If you think about it, this makes sense - how else could you tell it to run the command VAR with its first argument being "=" and its second argument being "value"? Enter the following code into var.sh:

This assigns the string "Hello World" to the variable MY_MESSAGE then echo es out the value of the variable. Note that we need the quotes around the string Hello World. Whereas we could get away with echo Hello World because echo will take any number of parameters, a variable can only hold one value, so a string with spaces must be quoted so that the shell knows to treat it all as one. Otherwise, the shell will try to execute the command World after assigning MY_MESSAGE=Hello

The shell does not care about types of variables; they may store strings, integers, real numbers - anything you like. People used to Perl may be quite happy with this; if you've grown up with C, Pascal, or worse yet Ada, this may seem quite strange. In truth, these are all stored as strings, but routines which expect a number can treat them as such. If you assign a string to a variable then try to add 1 to it, you will not get away with it:

This is because the external program expr only expects numbers. But there is no syntactic difference between:

Note though that special characters must be properly escaped to avoid interpretation by the shell. This is discussed further in Chapter 6, Escape Characters .

We can interactively set variable names using the read command; the following script asks you for your name then greets you personally:

Mario Bacinsky kindly pointed out to me that I had originally missed out the double-quotes in the final line, which meant that the single-quote in the word "you're" was unmatched, causing an error. It is this kind of thing which can drive a shell programmer crazy, so watch out for them!

Scope of Variables

Variables in the Bourne shell do not have to be declared, as they do in languages like C. But if you try to read an undeclared variable, the result is the empty string. You get no warnings or errors. This can cause some subtle bugs - if you assign MY_OBFUSCATED_VARIABLE=Hello and then echo $MY_OSFUCATED_VARIABLE Then you will get nothing (as the second OBFUSCATED is mis-spelled).

There is a command called export which has a fundamental effect on the scope of variables. In order to really know what's going on with your variables, you will need to understand something about how this is used.

Create a small shell script, myvar2.sh :

Now run the script:

MYVAR hasn't been set to any value, so it's blank. Then we give it a value, and it has the expected result. Now run:

It's still not been set! What's going on?! When you call myvar2.sh from your interactive shell, a new shell is spawned to run the script. This is partly because of the #!/bin/sh line at the start of the script, which we discussed earlier . We need to export the variable for it to be inherited by another program - including a shell script. Type:

Now look at line 3 of the script: this is changing the value of MYVAR . But there is no way that this will be passed back to your interactive shell. Try reading the value of MYVAR :

Once the shell script exits, its environment is destroyed. But MYVAR keeps its value of hello within your interactive shell. In order to receive environment changes back from the script, we must source the script - this effectively runs the script within our own interactive shell, instead of spawning another shell to run it. We can source a script via the "." (dot) command:

The change has now made it out into our shell again! This is how your .profile or .bash_profile file works, for example. Note that in this case, we don't need to export MYVAR . An easy mistake to make is to say echo MYVAR instead of echo $MYVAR - unlike most languages, the dollar ( $ ) symbol is required when getting the value of a variable, but must not be used when setting the value of the variable. An easy mistake to make when starting out in shell scripting. One other thing worth mentioning at this point about variables, is to consider the following shell script:

Think about what result you would expect. For example, if you enter "steve" as your USER_NAME, should the script create steve_file ? Actually, no. This will cause an error unless there is a variable called USER_NAME_file . The shell does not know where the variable ends and the rest starts. How can we define this? The answer is, that we enclose the variable itself in curly brackets :

The shell now knows that we are referring to the variable USER_NAME and that we want it suffixed with " _file ". This can be the downfall of many a new shell script programmer, as the source of the problem can be difficult to track down.

Also note the quotes around "${USER_NAME}_file" - if the user entered "Steve Parker" (note the space) then without the quotes, the arguments passed to touch would be Steve and Parker_file - that is, we'd effectively be saying touch Steve Parker_file , which is two files to be touch ed, not one. The quotes avoid this. Thanks to Chris for highlighting this.

Get this tutorial as a PDF for only $5

My Paperbacks and eBooks

My Shell Scripting books, available in Paperback and eBook formats. This tutorial is more of a general introduction to Shell Scripting, the longer Shell Scripting: Expert Recipes for Linux, Bash and more book covers every aspect of Bash in detail.

Bash Variables Explained: A Simple Guide With Examples

Master Bash variables with the help of these explanations and examples.

Variables are used for storing values of different types during program execution. There are two types of variables in Bash scripting: global and local.

Global variables can be used by all Bash scripts on your system, while local variables can only be used within the script (or shell) in which they're defined.

Global variables are generally provided on the system by default and are mainly environment and configuration variables. Local variables, on the other hand, are user-defined and have arbitrary uses.

Bash Local Variables

To create a variable, you need to assign a value to your variable name. Bash is an untyped language, so you don't have to indicate a data type when defining your variables.

Bash also allows multiple assignments on a single line:

Just like many other programming languages, Bash uses the assignment operator = to assign values to variables. It's important to note that there shouldn't be any spaces on either side of the assignment operator. Otherwise, you'll get a compilation error.

Related: What Does "Bash" Mean in Linux?

Another key point to note: Bash doesn't allow you to define a variable first and then assign a value to it later. You must assign a value to the variable at creation.

Sometimes, you may need to assign a string that has a space in it to your variable. In such a case, enclose the string in quotes.

Notice the use of single quotes. These quotes are also called "strong quotes" because they assign the value precisely as it's written without regard to any special characters.

In the example above, you could have also used double quotes ("weak quotes"), though this doesn't mean they can always be used interchangeably. This is because double quotes will substitute special characters (such as those with $ ), instead of interpreting them literally.

See the example below:

If you want to assign a command-line output to your variable, use backquotes ( `` ). They'll treat the string enclosed in them as a terminal command and return its result.

Parameter Expansion in Bash

Parameter Expansion simply refers to accessing the value of a variable. In its simplest form, it uses the special character $ followed by the variable name (with no spaces in between):

You can also use the syntax ${variableName} to access a variable's value. This form is more suitable when confusion surrounding the variable name may arise.

If you leave out the curly brackets, ${m}ical will be interpreted as a compound variable (that doesn't exist). This use of curly brackets with variables is known as "substitution".

Global Variables

As mentioned earlier, your Linux system has some built-in variables that can be accessed across all of your scripts (or shells). These variables are accessed using the same syntax as local variables.

Related: How to Create and Execute Bash Scripts in Linux

Most of these variables are in BLOCK letters. However, some are single characters that aren't even alphanumeric characters.

Here are some common useful global variables:

HOME : Provides the user's home directory

SHELL : Provides the type of shell you're using (e.g Bash, csh..etc)

? : Provides the exit status of the previous command

To get a list of global variables on your system, run the printenv (or env) command:

Loops in Bash Scripting

Now you know what variables are, how to assign them, and how to perform basic Bash logic using them.

Loops enable you to iterate through multiple statements. Bash accommodates for loops and while loops with a simple syntax for all of your looping needs.

If you're mastering the art of Bash development, for loops ought to be next up on your list.

We Love Servers.

  • WHY IOFLOOD?
  • BARE METAL CLOUD
  • DEDICATED SERVERS

Bash ‘Declare’ Command Guide for Variable Assignment

Stylized terminal interface illustrating Bash declare command with abstract data structures

Are you finding it challenging to master the use of bash declare? You’re not alone. Many developers grapple with this task, but there’s a tool that can make this process a breeze.

Like a skilled craftsman, bash declare helps you shape your variables with precision. These variables can be used in any bash script, making bash declare an essential tool for any bash programmer.

This guide will walk you through the use of bash declare, from basic syntax to advanced techniques. We’ll explore bash declare’s core functionality, delve into its advanced features, and even discuss common issues and their solutions.

So, let’s dive in and start mastering bash declare!

TL;DR: How Do I Use Bash Declare?

The bash declare command is used to declare variable types or assign them attributes, with the syntax, declare -[option] variableName=value . It’s a powerful tool that can help you manage your bash scripting more effectively.

Here’s a simple example:

In this example, we use the bash declare command to declare an integer variable num and assign it a value of 10. The -i option tells bash that num is an integer. When we echo num , it outputs the value 10.

This is just a basic usage of bash declare, but there’s much more to it. Continue reading for more detailed information and advanced usage scenarios.

Table of Contents

Grasping the Basics of Bash Declare

Diving deeper: advanced usage of bash declare, exploring alternatives: the ‘typeset’ command, troubleshooting common errors with bash declare, the foundation: bash scripting and variables, bash declare in real-world applications, wrapping up: mastering bash declare for efficient scripting.

Bash declare is a built-in command in the bash shell that allows you to declare variable types or assign attributes to variables. It’s a fundamental tool for any bash programmer, and understanding its basic syntax and functionality is crucial.

Let’s take a look at a simple example of how to use bash declare:

In this example, we use bash declare to declare a read-only variable var and assign it a string value ‘Hello, World!’. The -r option tells bash that var is read-only, meaning it can’t be modified or unset once it’s been set. When we echo var , it outputs the string ‘Hello, World!’.

Understanding the basic usage of bash declare is the first step towards mastering more complex bash scripting. It gives you control over your variables, allowing you to define their behavior and prevent unwanted changes. However, it’s important to note that declaring a variable as read-only can lead to errors if you later attempt to modify it. Therefore, it’s crucial to use this feature carefully.

As you become more comfortable with bash declare, you can start exploring its more advanced features. Bash declare isn’t limited to defining read-only variables; it can also be used to declare integer variables, array variables, and more.

Declaring Integer Variables

One such advanced usage is declaring integer variables. This can be useful when you need to perform arithmetic operations in your bash script. Let’s take a look at an example:

In this code block, we first declare an integer variable num . We then assign a default value of 5 to num and multiply it by 10. When we echo num , it outputs the result of the multiplication: 50. This demonstrates how bash declare can be used to perform arithmetic operations directly within the assignment.

Declaring Read-Only Variables

Another advanced use of bash declare is declaring read-only variables. This can be beneficial when you want to prevent a variable from being modified after its initial assignment. Here’s an example:

In this code block, we declare a read-only variable var and attempt to change its value. However, bash prevents us from doing so, and instead outputs an error message. This highlights the power of bash declare in preserving the integrity of your variables.

Keep in mind, while these advanced features of bash declare can be quite useful, they should be used judiciously. Declaring a variable as an integer or read-only can restrict its functionality, so it’s important to consider the implications before using these options.

While bash declare is an incredibly versatile tool, it’s not the only command available for managing variable types and attributes in bash scripting. Another command that offers similar functionality is typeset .

The ‘typeset’ Command and Its Usage

The typeset command, like bash declare , allows you to declare variable types or assign attributes. In fact, in many cases, typeset can be used as a substitute for bash declare . Let’s look at an example:

In this code block, we use typeset to declare an integer variable num and assign it a value of 20. When we echo num , it outputs the value 20. This is similar to how we used bash declare to declare and assign an integer variable in the earlier examples.

Weighing the Pros and Cons

While typeset can be used as an alternative to bash declare , it’s worth noting that typeset is older and less commonly used in modern bash scripting. However, it remains a viable option, especially for scripts that need to be compatible with older versions of bash.

On the other hand, bash declare is more widely recognized and used in modern bash scripting. It’s also more intuitive for those who are new to bash scripting, as its name clearly indicates its purpose.

In conclusion, while typeset is a viable alternative to bash declare , it’s generally recommended to use bash declare unless you have a specific reason to use typeset . Understanding both commands, however, can give you more flexibility and control in your bash scripting.

While bash declare is a powerful tool, it’s not without its quirks and potential pitfalls. Here, we’ll explore some common errors you might encounter when using bash declare, and provide solutions to overcome them.

Error: Modifying a Read-Only Variable

One common error occurs when you try to modify a read-only variable. Let’s look at an example:

In this code block, we declare a read-only variable var and then attempt to change its value. However, bash prevents us from doing so, outputting an error message. The solution here is simple: avoid modifying read-only variables once they’ve been declared.

Error: Incorrect Usage of Integer Variables

Another common mistake is incorrectly using integer variables. For example:

In this case, we’ve declared num as an integer variable but attempted to assign a string value to it. Bash defaults the value to 0, as it expects an integer. To avoid this, ensure you assign appropriate values to your variables based on their declared type.

Best Practices and Optimization

To avoid common errors and optimize your use of bash declare, here are a few tips:

  • Always assign appropriate values to your variables based on their declared type.
  • Avoid modifying read-only variables once they’ve been declared.
  • Use meaningful variable names to make your code more readable and maintainable.

By keeping these considerations in mind, you can avoid common pitfalls and make the most of bash declare in your scripting.

To fully understand the power of bash declare, it’s essential to grasp the fundamentals of bash scripting and variables.

Bash scripting is a form of programming that uses the bash shell, a command-line interface for Unix-based systems. It allows you to automate tasks, manipulate files, and perform complex operations.

At the heart of bash scripting are variables. Variables in bash are like containers that hold information. This information can be a number, a string, or even the result of a command. Variables are declared and assigned values using the equals (=) sign, like so:

In this example, we declare a variable var and assign it a string value ‘Hello, World!’. When we echo var , it outputs the string ‘Hello, World!’.

The Importance of Variable Types and Attributes

In bash scripting, variables are untyped by default, meaning they can hold any type of data. However, sometimes it’s useful to specify a variable’s type or assign it certain attributes. This is where the bash declare command comes into play.

By using bash declare, you can define a variable’s type (such as integer or read-only), which can help prevent errors and make your code more robust. For example, declaring a variable as an integer ensures that it can only hold integer values, which can be useful when performing arithmetic operations.

In addition, bash declare allows you to assign attributes to variables, such as making them read-only or assigning them a default value. These attributes can help control how your variables behave and prevent unwanted modifications.

In conclusion, understanding the fundamentals of bash scripting and the importance of variable types and attributes is key to mastering bash declare. With this knowledge, you can write more effective and error-free bash scripts.

Bash declare is not just a standalone command; it’s a vital part of larger scripts and projects. It can be used in conjunction with other commands and functions to create more complex and powerful bash scripts.

Applying Bash Declare in Larger Scripts

In larger scripts, bash declare can be used to manage variables more effectively. For instance, you might use bash declare to set default values for variables, declare them as integers for arithmetic operations, or even make them read-only to prevent unwanted modifications.

Complementary Commands and Functions

Bash declare often works hand in hand with other commands and functions. For example, the echo command is frequently used with bash declare to output the value of a variable. Similarly, the unset command can be used to unset a variable that has been declared but is no longer needed.

Further Resources for Mastering Bash Declare

If you’re looking to delve deeper into bash declare and related topics, here are a few resources that might help:

  • Advanced Bash-Scripting Guide : This guide offers in-depth information on bash scripting, including the use of bash declare.
  • GNU Bash Reference Manual : This is the official reference manual for bash, featuring a comprehensive section on bash declare.
  • Bash Guide for Beginners : This guide is perfect for beginners looking to understand the basics of bash scripting, including bash declare.

With these resources and the information provided in this guide, you’re well on your way to mastering bash declare and its applications in bash scripting.

In this comprehensive guide, we’ve navigated the intricacies of bash declare, a powerful command in bash scripting for managing variable types and attributes.

We began with the basics, learning how to use bash declare for simple tasks like declaring variables and assigning them values. We then delved into more advanced usage, exploring how to declare integer variables, read-only variables, and more. Along the way, we provided practical code examples to illustrate each concept and its application.

We also tackled common challenges you might encounter when using bash declare, such as modifying a read-only variable or incorrectly using integer variables, providing solutions for each issue. Additionally, we explored the ‘typeset’ command as an alternative to bash declare, giving you a broader view of the tools available for variable management in bash scripting.

Here’s a quick comparison of bash declare and typeset:

Whether you’re just starting out with bash scripting or you’re looking to level up your skills, we hope this guide has given you a deeper understanding of bash declare and its capabilities.

With its ability to manage variable types and attributes, bash declare is a vital tool for efficient and robust bash scripting. Now, you’re well equipped to harness its power in your scripts. Happy coding!

About Author

Gabriel Ramuglia

Gabriel Ramuglia

Gabriel is the owner and founder of IOFLOOD.com , an unmanaged dedicated server hosting company operating since 2010.Gabriel loves all things servers, bandwidth, and computer programming and enjoys sharing his experience on these topics with readers of the IOFLOOD blog.

Related Posts

Visualization of the cut command in Linux displaying scissors and segment markers symbolizing data selection and text processing

refine App screenshot

Struggling with internal tools?

Explore refine’s limitless possibilities in crafting CRUD apps, CRM solutions, HR dashboards, and more!

Using Arguments in Bash Scripts

Using Arguments in Bash Scripts

Introduction ​.

Arguments in any bash script are inevitable for any scripting task. They make the script flexible and dynamic instead of static and hard coded. Now there are many variations in how arguments can be used effectively in a script, and this is exactly what we will discuss today. Remember, a solid understanding of arguments is crucial to automate your tasks through script arguments. For each point in this article, we will provide an example from a practical perspective as well.

Let's start with understanding how positional parameters work in the bash script.

Steps to be covered:

  • Understanding Positional Parameters
  • Using Special Parameters
  • Implementing Flags and Options
  • Best Practices for Bash Script Arguments

Understanding Positional Parameters ​

In bash scripting, positional parameters are a fundamental concept. They’re the variables that bash scripts use to handle input data. When you run a script, you can pass arguments to it, and these arguments are stored in special variables known as positional parameters. The first argument you pass is stored in $1 , the second in $2 , and so on.

Let’s understand this in detail through an example. Let's say you have a bash script that needs to process three pieces of input data and you want to make use of positional parameters. The below snippet shows how you might use positional parameters to handle this:

When you run this script with three arguments, it will echo back the first three arguments you passed to it. For instance, if you run ./myscript.sh marketing sales engineering , the script will output:

This shows how $1 , $2 , and $3 correspond to the first, second, and third arguments you passed to the script. It is a simple yet powerful way to make your scripts more flexible and reusable.

Using Special Parameters ​

In bash scripting, there are special parameters that provide additional ways to handle input data. These include $* , $@ , and $# .

The $* and $@ parameters represent all arguments that were passed to the script. While they might seem identical, their behavior diverges when you try to iterate over them in a script. Let’s illustrate this with an example:

If you run this script with the arguments ./myscript.sh one two three , you’ll notice that $* treats all arguments as a single string, while $@ treats each argument as a separate string.

The $# parameter is different - it doesn’t represent the arguments themselves, but the number of arguments. This can be useful when your script needs to know how many arguments were passed. Here’s a simple script that uses $# :

If you run ./myscript.sh apple banana cherry , the script will output You provided 3 arguments. This shows how $# can be used to count the number of arguments passed to a script.

Implementing Flags and Options ​

Bash scripts often require input parameters to customize behavior, and getopts is a utility that can be used to parse positional parameters.

In the script above, -h is used for displaying help information, and -n is used for setting a name. The v flag is used to set verbose mode. If -v is provided when the script is run, verbose is set to 1. If -n is provided, the next argument is assigned to the variable name .

Here’s an example of how you might run this script:

In this example, the -v flag sets verbose mode, and -n sets the name to “Example Name”. Any arguments provided after the flags (in this case, “leftover args”) are still available in the script.

Handling Variable Numbers of Arguments ​

Bash scripts often need to accept a variable number of arguments. This is where $@ comes into play. It’s a special shell variable that holds all the arguments provided to the script.

In the script above, we initialize an empty string concatenated . We then loop through all arguments provided to the script using $@ and append each argument to concatenated .

In this example, the script concatenates the three arguments arg1 , arg2 , and arg3 into a single string. This demonstrates how a bash script can handle a variable number of arguments.

Best Practices for Script Arguments ​

Here are some best practices for designing bash scripts with arguments:

Use Intuitive Argument Names: Opt for descriptive and intuitive names for arguments. This improves readability and helps maintain the code.

  • Bad: bash script.sh $1 $2
  • Good: bash script.sh -u username -p password

Assign Default Values: Where practical, assign default values to arguments. This ensures that your script behaves predictably even when certain inputs are omitted.

  • Example: file_path=${1:-"/default/path"}

Inline Comments: Use inline comments to explain the purpose and expected values of arguments. This documentation aids future maintainers and users of your script.

  • Example: # -u: Username for login

Leverage getopts for Option Parsing: getopts allows for more flexible and robust argument parsing, supporting both short and long options.

  • Bad: if [ -z $var ]; then
  • Good: if [ -z "$var" ]; then
  • Add set -u at the beginning of your script.

Conclusion ​

The importance of arguments in developing scripts that can adapt to different situations is highlighted by the fact that they are extensively used in bash scripts. We focused on improving script functionality and user interaction by using positional parameters, special variables, and getopts .

Not only do the given examples provide a useful roadmap, but they also inspire developers to try new things and incorporate these ideas into their scripts. Your scripting skills will certainly improve after adopting these best practices and techniques, allowing you to make your automation tasks more efficient and adaptable.

Related Articles

We'll go over the basics of Docker networking, including the default networks, bridge networking, host networking, overlay networking, Macvlan networking, and custom bridge networking.

We will learn how to set up Astrojs, create a new project, and basics.

We'll explore the key differences between GraphQL and REST, and discuss the use cases where each approach excels.

  • Introduction
  • Handling Variable Numbers of Arguments
  • Best Practices for Script Arguments

LinuxSimply

Home > Bash Scripting Tutorial > Bash Functions > Argument in Bash Script

Argument in Bash Script

Md Zahidul Islam Laku

Proper execution of a Bash script depends on the successful parsing of its arguments. After parsing the arguments users need to access those using the correct syntax within the script. Bash allows the manipulation of command line arguments passed to a script. But figuring out how to do this in a Bash script can sometimes be tricky. In this article, I will discuss all the concerns Bash users have about arguments in a script.

Syntax for Passing Arguments to Bash Script

To pass arguments to a Bash script, simply list them after the script’s name when invoking the script from the terminal. For example:

Here, arg1, arg2 and arg3 are three arguments passed to the script named script.sh .

How to Access Arguments in Bash Script

There are a couple of ways to access arguments passed to a Bash script. Most Bash users utilize positional parameters to process arguments in a script. Though less popular, the getopts command to access command line arguments is equally handy.

1. Using Positional Parameters

Arguments passed to a script can be accessed using positional parameters like $1, $2, $3, etc. These parameters correspond to the first, second, third and subsequent arguments provided to the script. Look at the example below to understand how it works:

The script prints a message in the terminal using the echo command . It uses $1 (first positional parameter) to access the argument provided to the script.

Accessing argument in Bash script using positional parameter

2. Using “getopts” Command

The getopts command with OPTAG environment can process command line options and arguments. One can provide single or multiple arguments under an option using the getopts command. Here is an example of how getopts handle arguments in Bash script:

This Bash script utilizes the getopts command to parse command-line options and arguments. It expects two options: -n , which takes an argument called processname , and -i , which takes an argument called id .

Inside a while loop, it uses a case statement to handle each option. When -n is encountered, it assigns the following argument to the “processname” variable. On the contrary, when -i is encountered, it assigns the following argument to the “id” variable. After parsing the options, it prints out the values of “processname” and “id”.

Accessing argument in Bash script using the getopts command

How to Check the Number of Arguments in Bash Script

Use the special variable $# to check the number of arguments passed to a script. This variable is used for storing the number of command-line arguments. If there is no argument, then the value of $# will be 0 . Here is an example:

Getting number of arguments passed to a script

How to Get All the Arguments Passed to a Script

To get all the arguments passed to a script, use the special variables S@ or S* . These two variables contain the array of all input parameters provided to a script. However, the value of these variables may differ depending on whether they are quoted or not.

1. Utilizing $@ to Get All Command Line Arguments

The $@ variable holds all the arguments passed to a script. Therefore, it is used to get all the command line arguments. Here’s how:

Getting all the command line argument of a Bash script

Double-quoted (“$@”) and unquoted ($@) may behave differently. “$@” expands to an array of separate strings containing the arguments. On the other hand, $@ splits the input arguments into words separated by space (Or based on the first field of the IFS variable). The difference is visible when you iterate over the input arguments using a for loop :

This Bash script demonstrates the difference between using $@ and “$@” by iterating over the command-line arguments.

In the first loop, $@ is used without quotes, causing word splitting to occur. By default, words are separated by space. Hence a single argument can be separated into multiple words if it contains space.

In contrast, the second loop uses "$@" with double quotes, preserving each argument as a separate string. This ensures that arguments containing spaces or special characters are treated as single units.

Difference between quoted and unquoted $@

2. Utilizing $* to Get All Command Line Arguments

Similar to $@, $*   is used to get all the command line arguments.

Getting all command line arguments

Again, double-quoted and unquoted $* behave differently. “$*” expands to a single string. On the contrary, $* splits into words separated by space (Or based on the first field of the IFS variable). Let’s visualize the difference using a for loop:

This Bash script illustrates the difference between using “$*” and $* to iterate over command-line arguments.

In the first loop, double-quoted “$*” causes all command-line arguments to be expanded into a single string. Consequently, the loop iterates only once, printing all arguments as a single string. Conversely, in the second loop, $* is used without double quotes, causing word splitting to occur. Hence, any separation by space in the arguments is treated as a separate word, leading to one more iteration of the loop.

Difference while gettting all arguments of a bash script

What is the Difference Between “$@” and “$*”

The main difference between “$@” and “$” is that “$@” expands to a string for each command line argument. Whereas “$*” expands into a single string with all of the words parsed as arguments. This is easy to understand with the following example:

In the first for loop the script iterates over command line arguments using “$@”. It initializes a counter i to track the number of iterations. It proceeds to traverse each argument individually through a for loop, printing each argument and incrementing i accordingly. Finally, the script outputs the total number of iterations, reflecting the count of command-line arguments.

In the second portion, it program uses “$*” to iterate over arguments. This time it initializes a counter j . Again the script attempts to print each argument stored in  “$*” while incrementing j in each iteration.

Difference while gettting all arguments of a bash script

On the other hand, "$*" expands to a single string containing all the arguments concatenated together. Therefore, when iterating over “$*” , the loop runs only once since there is only one element in the array.

How to Shift Command Line Arguments in Bash Script

Shifting command-line arguments in a Bash script allows you to access subsequent arguments by adjusting their positional index. The shift command is used for this purpose. After calling shift , the $1 will be the value of $2, $2 will be the value of $3 and so on. The following script demonstrates the shifting of command line arguments:

Shifting argument to the left by 1

Moreover, one can provide a number as an argument to the shift command. shift n (n is the number) causes the positional parameters to be shifted left by n positions. For instance, shift 3 causes the fourth argument to become accessible by $1, and the fifth argument becomes accessible by $2 and so on.

Shifting argument by n position to the left using shift command

How to Change Command Line Arguments in Bash

In a Bash script, you can change command-line arguments by assigning them to variables within the script. This approach allows you to manipulate the arguments without directly modifying them. Here’s an example:

This script assigns the first two command-line arguments to variables arg1 and arg2 . It then modifies the value of “arg1” by assigning it the string “Nan”. Finally, it prints the modified value of “arg1”.

Changing argument using variable within a script

The set command provides a direct way to modify the command line arguments. The following script shows how the set command can be used to update the arguments:

This script updates the arguments passed to it by replacing the third argument with “Nan” while preserving the first two arguments and those from the fourth onwards. It achieves this by using the set -- command to redefine the entire argument list. The ${@:1:2} syntax selects the first two arguments, and ${@:4} selects all arguments from the fourth position onwards, effectively excluding the third argument. “Nan” in the middle sets the new value of the third argument.

Finally, the script echoes the updated arguments using $@ and displays the third argument separately using $3.

Changing command line argument uisng set command

Practice Tasks on Bash Script Argument

Write a bash script named myscript.sh that takes 10 arguments as follows:

  • Echo the first and last argument using positional parameter?
  • Change the fifth argument to “Null” and access it using positional parameter $5?
  • Shift the arguments so that you can access the last argument using the first positional parameter ($1)?
  • Print all the arguments using $@ and $*?
  • Use a for loop to iterate over “$@” and “$*”. Determine how many times the loop runs?

In conclusion, Bash provides various methods for accessing and modifying arguments passed to a script. Positional parameters serve as the default choice for this purpose. Additionally, special variables such as “$@” or “$*” allow users to examine all command-line arguments. Furthermore, the process of shifting command-line arguments enables users to alter the positional index of arguments. Finally, the set built-in allows direct modification of command-line arguments within the script

People Also Ask

What is the meaning of $0 in the bash shell.

The special variable $0 refers to the name of the script that is currently being executed. For example, if you run a script named myscript.sh using the command ./myscript.sh , then within the script, the value of $0 would be myscript.sh .

How to access command line arguments after the first 9 positional parameters?

To access command line arguments beyond the first 9 positional parameters in a bash script, you can use ${10}, ${11}, and so on. This allows you to access arguments beyond the positional parameters 0 through 9. Don’t use $10 without curly braces. This will expand to the first positional parameter($1) and then add the literal 0 after the expansion.

Which one should I prefer between “$@” and “$*” to get all the arguments?

To get all command line arguments in a bash script, “$@” is generally preferred over “$*”. Because “$@” treats each command-line argument as a separate entity. While “$*” expands to a single string containing all the arguments.

How to pass a file as an argument to a bash script?

To pass a file as an argument to a Bash script, you would typically provide the filename as an argument when running the script from the command line. Here’s how you can do it:

To access the contents of the file inside the script use the corresponding positional parameter:

Why “argument list too long” error occur in Bash?

The “argument list too long” error occurs in Bash when someone attempts to pass a large number of arguments to a bash script or a command that exceeds the predefined argument limit of the system. The limit is typically around 100,000 arguments. This limit is imposed to prevent memory overflow and ensure system stability.

Md Zahidul Islam Laku

Md Zahidul Islam Laku

Hey, I'm Zahidul Islam Laku currently working as a Linux Content Developer Executive at SOFTEKO. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). I write articles on a variety of tech topics including Linux. Learning and writing on Linux is nothing but fun as it gives me more power on my machine. What can be more efficient than interacting with the Operating System without Graphical User Interface! Read Full Bio

Leave a Comment Cancel reply

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

IMAGES

  1. Bash Function & How to Use It {Variables, Arguments, Return}

    variable assignment bash script

  2. Bash Script: Set variable example

    variable assignment bash script

  3. Bash Scripting

    variable assignment bash script

  4. Bash Script Variables

    variable assignment bash script

  5. Bash Function & How to Use It {Variables, Arguments, Return}

    variable assignment bash script

  6. Bash Scripting Tutorials

    variable assignment bash script

VIDEO

  1. Working with BASH shell

  2. Bash Scripts to Automate the task Examples || Bash tutorial in Hindi

  3. Java Script Assignment

  4. Computer Systems Bash Assignment

  5. Unit 9 Video Assignment

  6. Section-5: Vidoe-10 : Command Line Arguments to provide inputs for Variables of Bash Shell Script

COMMENTS

  1. How to Work with Variables in Bash

    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.

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

    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.

  3. How to Use Variables in Bash Shell Scripts

    Using variables in bash shell scripts In the last tutorial in this series, you learned to write a hello world program in bash. #! /bin/bash echo 'Hello, World!' That was a simple Hello World script. Let's make it a better Hello World. Let's improve this script by using shell variables so that it greets users with their names.

  4. Bash Script: Set variable example

    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.

  5. Variable Declaration and Assignment

    In Bash, declaring variables and assigning values to them can be done for different data types by using different options along with the declare command. However, you can also declare and assign the variable value without explicitly specifying the type. 3.

  6. Introduction to Variables in Bash Scripting [An Ultimate Guide]

    You can assign the output of a command to a variable using command substitution. Enclose the command within backticks () or use the $ (command) syntax. For example, variable=command or variable=$ (command). When using variables within quotes, consider the type of quoting to preserve the value.

  7. Bash Variables

    A Bash variable in Linux is a symbolic name or identifier that stores a value or text string. It is a way to store and manipulate data within a Bash script or the Bash environment. Variables in Bash scripts are typically used to hold temporary or user-defined data, making it easier to reference and manipulate values as needed.

  8. How to Set Variables in Bash: Shell Script Syntax Guide

    To set a variable in Bash, you use the '=' operator with the syntax, VAR=Value. There must be no spaces between the variable name, the '=' operator, and the value you want to assign to the variable. Here's a simple example: VAR='Hello, World!' echo $VAR # Output: # 'Hello, World!'

  9. Understanding Shell Script Variables

    In the first case, the shell sees the "=" symbol and treats the command as a variable assignment. In the second case, the shell assumes that VAR must be the name of a command and tries to execute it. ... Shell Scripting: Expert Recipes for Linux, Bash and more is my 564-page book on Shell Scripting. The first half covers all of the features of ...

  10. Linux Bash: Multiple Variable Assignment

    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.

  11. How to Declare Variable in Bash Scripts? [5 Practical Cases]

    In Bash scripting, you can use the declare command to declare variables explicitly and set their attributes. The basic syntax of the "declare" command is: declare [options] variable_name=value Useful Options Using options with the declare command provides explicit control and customization over the variable declaration.

  12. Variable Assignment

    Variable Assignment 4.2. 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

  13. bash

    4 Answers Sorted by: 1063 This technique allows for a variable to be assigned a value if another variable is either empty or is undefined. NOTE: This "other variable" can be the same or another variable. excerpt ${parameter:-word} If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

  14. Bash Variables Explained: A Simple Guide With Examples

    Bash Local Variables . To create a variable, you need to assign a value to your variable name. Bash is an untyped language, so you don't have to indicate a data type when defining your variables. var1=Hello. Bash also allows multiple assignments on a single line: a=6 b=8 c=9. Just like many other programming languages, Bash uses the assignment ...

  15. Bash 'Declare' Command Guide for Variable Assignment

    The bash declare command is used to declare variable types or assign them attributes, with the syntax, declare -[option] ... it's essential to grasp the fundamentals of bash scripting and variables. Bash scripting is a form of programming that uses the bash shell, a command-line interface for Unix-based systems. It allows you to automate ...

  16. Assigning default values to shell variables with a single command in bash

    I have a whole bunch of tests on variables in a bash (3.00) shell script where if the variable is not set, then it assigns a default, e.g.: if [ -z "${VARIABLE}" ]; then FOO='default' else FOO=${VARIABLE} fi I seem to recall there's some syntax to doing this in one line, something resembling a ternary operator, e.g.:

  17. Re-assigning (specifically, incrementing) a variable in a bash script

    How can I do command line integer & float calculations, in bash, or any language available? I would like to simply re-assign a variable (to be specific, increment it by 0.050) in a bash script. In the following script that I wrote, i is an (integer) index, and mytime is a decimal/double/float number. "ps" (picosecond) is the unit of time that I ...

  18. How to Assign Default Value to a Variable Using Bash

    When dealing with variables in shell scripting, it's important to account for the fact that a variable may have one of several states:. assigned value; unset; null string; Thus, to avoid unexpected errors, we can use the ${param:-param} expression along with similar expressions to assign a default value to a variable under specific conditions.. In this tutorial, we'll explore how to assign ...

  19. Bash Variable Naming Conventions in Shell Script [6 Rules]

    Rule 02: Avoid Using Number at the Beginning of the Variable Name. When it comes to naming variables in Bash shell scripts, one important convention to follow is to avoid using a numeric digit as the first character of a variable name. Here is a sample example demonstrated below where I created several variables placing the number digit at the ...

  20. Using Arguments in Bash Scripts

    They're the variables that bash scripts use to handle input data. When you run a script, you can pass arguments to it, and these arguments are stored in special variables known as positional parameters. ... Good: bash script.sh -u username -p password; Assign Default Values: Where practical, assign default values to arguments. This ensures ...

  21. Argument in Bash Script

    This Bash script utilizes the getopts command to parse command-line options and arguments. It expects two options: -n, which takes an argument called processname, and -i, which takes an argument called id. Inside a while loop, it uses a case statement to handle each option. When -n is encountered, it assigns the following argument to the "processname" variable.

  22. Solved In this problem set, you will create a BASH script

    Question: In this problem set, you will create a BASH script that will declare and initialize a variable with a specific value. You will then recall that variable in a sentence that will be output to the screen.To do before scripting:Create a folder (/home//scripts/) where you can store all of your scripts.