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.

We Love Servers.

  • WHY IOFLOOD?
  • BARE METAL CLOUD
  • DEDICATED SERVERS

How to Set Variables in Bash: Shell Script Syntax Guide

Bash script setting a variable depicted with assignment symbols and variable name icons highlighting equal signs and data assignment markers

Do you find setting variables in Bash a bit tricky? You’re not alone. Many developers find Bash variable assignment a bit puzzling, but we’re here to help! You can think of Bash variables as small storage boxes – they allow us to store data temporarily for later use, providing a versatile and handy tool for various tasks.

In this guide, we’ll walk you through the process of setting variables in Bash , from the basics to more advanced techniques. We’ll cover everything from simple variable assignment, manipulating and using variables, to more complex uses such as setting environment variables or using special variable types.

So, let’s dive in and start mastering Bash variables!

TL;DR: How Do I Set a Variable in Bash?

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:

In this example, we’ve set a variable named VAR to the string ‘Hello, World!’. We then use the echo command to print the value of VAR , resulting in ‘Hello, World!’ being printed to the console.

This is just the basics of setting variables in Bash. There’s much more to learn about using variables effectively in your scripts. Continue reading for more detailed information and advanced usage scenarios.

Table of Contents

Bash Variable Basics: Setting and Using Variables

Advanced bash variable usage, alternative approaches to bash variables, troubleshooting bash variables: common pitfalls and solutions, understanding variables in programming and bash, expanding bash variable usage in larger projects, wrapping up: mastering bash variables.

In Bash, setting a variable is a straightforward process. It’s done using the ‘=’ operator with no spaces between the variable name, the ‘=’ operator, and the value you want to assign to the variable. Let’s dive into a basic example:

In this example, we’ve created a variable named myVar and assigned it the value ‘Bash Beginner’. The echo command is then used to print the value of myVar , which results in ‘Bash Beginner’ being printed to the console.

The advantages of using variables in Bash are numerous. They allow you to store and manipulate data, making your scripts more flexible and efficient. However, there are potential pitfalls to be aware of. One common mistake is adding spaces around the ‘=’ operator when assigning values to variables. In Bash, this will result in an error.

Here’s what happens when you add spaces around the ‘=’ operator:

As you can see, Bash interprets myVar as a command, which is not what we intended. So, remember, no spaces around the ‘=’ operator when setting variables in Bash!

As you progress in Bash scripting, you’ll encounter instances where you need to use more advanced techniques for setting variables. One such technique is setting environment variables, which are variables that are available system-wide and to other programs. Another is using special variable types, such as arrays.

Setting Environment Variables

Environment variables are an essential part of Bash scripting. They allow you to set values that are going to be used by other programs or processes. To create an environment variable, you can use the export command:

In this example, we’ve created an environment variable called GREETING with the value ‘Hello, World!’. The export command makes GREETING available to child processes.

Using Array Variables

Bash also supports array variables. An array is a variable that can hold multiple values. Here’s how you can create an array variable:

In this case, we’ve created an array myArray containing three elements. We then print the second element (arrays in Bash are zero-indexed, so index 1 corresponds to the second element) using the echo command.

These are just a couple of examples of the more advanced ways you can use variables in Bash. As you continue to learn and experiment, you’ll find that variables are a powerful tool in your Bash scripting arsenal.

While setting variables in Bash is typically straightforward, there are alternative approaches and techniques that can offer more flexibility or functionality in certain scenarios. These can include using command substitution, arithmetic expansion, or parameter expansion.

Command Substitution

Command substitution allows you to assign the output of a command to a variable. This can be particularly useful for dynamic assignments. Here’s an example:

In this example, we’ve used command substitution ( $(command) ) to assign the current date to the myDate variable.

Arithmetic Expansion

Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result. For instance:

Here, we’ve used arithmetic expansion ( $((expression)) ) to add 5 and 5 and assign the result to the num variable.

Parameter Expansion

Parameter expansion provides advanced operations and manipulations on variables. This can include string replacement, substring extraction, and more. Here’s an example of string replacement:

In this case, we’ve used parameter expansion ( ${variable/search/replace} ) to replace ‘World’ with ‘Reader’ in the greeting variable.

These alternative approaches provide advanced ways of working with variables in Bash. They can offer more functionality and flexibility, but they also come with their own considerations. For instance, they can make scripts more complex and harder to read if not used judiciously. As always, the best approach depends on the specific task at hand.

While working with Bash variables, you might encounter some common errors or obstacles. Understanding these can help you write more robust and effective scripts.

Unassigned Variables

One common mistake is trying to use a variable that hasn’t been assigned a value. This can lead to unexpected behavior or errors. For instance:

In this case, because unassignedVar hasn’t been assigned a value, nothing is printed to the console.

Spaces Around the ‘=’ Operator

As mentioned earlier, adding spaces around the ‘=’ operator when assigning values to variables will result in an error:

Bash interprets myVar as a command, which is not what we intended. So, remember, no spaces around the ‘=’ operator when setting variables in Bash!

Variable Name Considerations

Variable names in Bash are case-sensitive, and can include alphanumeric characters and underscores. However, they cannot start with a number. Trying to create a variable starting with a number results in an error:

In this case, Bash doesn’t recognize 1var as a valid variable name and throws an error.

Best Practices and Optimization

When working with Bash variables, it’s good practice to use descriptive variable names. This makes your scripts easier to read and understand. Also, remember to unset variables that are no longer needed, especially in large scripts. This can help to optimize memory usage.

Understanding these common pitfalls and best practices can help you avoid errors and write better Bash scripts.

Variables are a fundamental concept in programming. In simple terms, a variable can be seen as a container that holds a value. This value can be a number, a string, a file path, an array, or even the output of a command.

In Bash, variables are used to store and manipulate data. The data stored in a variable can be accessed by referencing the variable’s name, preceded by a dollar sign ($).

Here is an example:

In this example, we have a variable named website that holds the value ‘www.google.com’. The echo command is used to print the value of the website variable, resulting in ‘www.google.com’ being output to the console.

Variables in Bash can be assigned any type of value, and the type of the variable is dynamically determined by the value it holds. This is different from some other languages, where the variable type has to be declared upon creation.

In addition to user-defined variables, Bash also provides a range of built-in variables, such as $HOME , $PATH , and $USER , which hold useful information and can be used in your scripts.

Understanding how variables work in Bash, and in programming in general, is crucial for writing effective scripts and automating tasks.

Setting variables in Bash is not just limited to small scripts. They play a crucial role in larger scripts or projects, helping to store and manage data effectively. The use of variables can streamline your code, making it more readable and maintainable.

Leveraging Variables in Scripting

In larger scripts, variables can be used to store user input, configuration settings, or the results of commands that need to be used multiple times. This can help to make your scripts more dynamic and efficient.

Accompanying Commands and Functions

When setting variables in Bash, you might often find yourself using certain commands or functions. These can include echo for printing variable values, read for getting user input into a variable, or unset for deleting a variable. Understanding these accompanying commands and functions can help you get the most out of using variables in Bash.

In this example, the read command is used to get user input and store it in the name variable. The echo command then uses this variable to greet the user.

Further Resources for Bash Variable Mastery

To deepen your understanding of Bash variables and their usage, you might find the following resources helpful:

  • GNU Bash Manual : This is the official manual for Bash, and it provides a comprehensive overview of all its features, including variables.

Bash Scripting Guide : This is a detailed guide to Bash scripting, with plenty of examples and explanations.

Bash Variables : This tutorial offers a detailed look at Bash variables, including their declaration, assignment, and usage.

These resources offer in-depth information about Bash variables and related topics, and can provide valuable insights as you continue your Bash scripting journey.

In this comprehensive guide, we’ve delved deep into the world of Bash variables. From simple variable assignment to more complex uses such as setting environment variables or using special variable types, we’ve covered it all.

We began with the basics, showing you how to set and use variables in Bash. We then explored more advanced techniques, such as setting environment variables and using array variables. Along the way, we also discussed alternative approaches, including command substitution, arithmetic expansion, and parameter expansion.

We also tackled common pitfalls and provided solutions to help you avoid these errors. Additionally, we compared the different methods of setting variables and their benefits, giving you a broader understanding of Bash variables.

Whether you’re just getting started with Bash scripting or you’re looking to advance your skills, we hope this guide has given you a deeper understanding of Bash variables and how to use them effectively.

Mastering Bash variables is a key step in becoming proficient in Bash scripting. With the knowledge and techniques you’ve gained from this guide, you’re now well-equipped to use variables effectively in your scripts. Happy scripting!

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

Linux terminal with fd command for file searching highlighted by search magnifying glass symbols and file directory icons emphasizing efficient file discovery

LinuxSimply

Home > Bash Scripting Tutorial > Parameters in Bash Scripting

Parameters in Bash Scripting

Mohammad Shah Miran

Bash scripting is a versatile way to integrate your algorithm with the Linux operating system. Central to its flexibility are parameters, which allow scripts to accept various inputs, adapt to different scenarios, and enhance reusability . This article explores the different aspects of parameters in Bash scripting , including positional , named , even alias parameters , and so on. So let’s start.

What is Bash Parameter?

A Bash parameter is a value or piece of information that is passed to a Bash script or function when it is executed. Parameters enable scripts to receive inputs , making them more versatile, adaptable, and user-friendly.

Think of Bash parameters as the secret ingredients you toss into a recipe to give it that extra specialty . They’re the values you pass to your scripts when you run them, opening up possibilities. Moreover, you can customize your scripts , make them user-friendly, and even handle unexpected twists and turns.

Let’s say you want to create a script that will greet someone whenever you pass any name to the script. Copy the following code in your nano editor and execute the file afterwards.

The first line of our code is a shebang , and it tells the system to execute the script using the Bash interpreter located at /bin/bash . By using the name=$1 , you’re assigning the value of the first positional parameter (provided when the script is run) to the variable name. The variable $1 holds the value of the first parameter passed to the script. Then, echo “Hello, $name!” line uses the echo command to print out a message. The string then takes the value of the $name variable and it displays the value.

Using Bash Parameter in a script

Types of Parameters in Bash Scripting

In Bash , parameters refer to the values or arguments provided to a script or command when it is executed. There are several ways to access these parameters within a script and you can divide all the parameters into several categories. Down below, I am going to discuss four different types of bash parameters.

1. Bash Positional Parameters

Positional parameters in Bash are a set of variables that capture and retain values passed as arguments when a script or command is invoked. The foremost among these parameters is $0 , which signifies the name of the script or command itself. It is essential for self-reference. Accompanying this is a sequence of $1 , $2 , $3 , and so on, representing the arguments provided in the order they appear. For instance, let’s have a look at the following code.

when executing the  ./script.sh arg1 arg2 , $1 corresponds to arg1 , and $2 corresponds to arg2 . The script will do certain types of work using those positional values. Additionally, $# holds the count of arguments passed, offering a numeric perspective on the provided inputs.

2. Bash Optional Parameters

In Bash scripting , optional parameters can also be implemented using flags or options . This approach allows users to provide specific options to the script, and the script responds accordingly. This is also known as bash parameter parsing . The getopts command is often used to handle such flags. It’s a built-in Bash command that simplifies the process of parsing command line options.

Optional parameters are often indicated through short or long options . Short options consist of a single character with a preceding dash (-) , while long options are comprised of words with two preceding dashes (–) . The syntax for denoting an optional parameter in Bash takes the form:

In this context, script_option.sh represents the script’s name , -s serves as a short option , –longoption functions as a long option , and argument stands as an optional argument that can be provided alongside the option. To use optional parameters in a Bash script, you can use the getopts command .

The basic syntax for using getopts is:

In this context, <options> represents a sequence of permissible options , <variable> denotes the variable designated for holding the current option , <option1> through <optionN> provides the potential options that the script is capable of receiving, and <command1> through <commandN> signify the actions that the script should carry out upon receiving the respective option.

By following the abovementioned syntax, you can also create named parameters to specify options and their corresponding values in a more intuitive and human-readable manner.

Named Parameters in Bash Scripts

Before going to delve into the topic, let’s first understand why you need to use the named parameter instead of using the positional parameter in the first place. As I have already discussed that positional arguments like $1 , $2 pass the command-line arguments. However, the effectiveness of positional arguments is inefficient   as it can become unclear which argument corresponds to which data type . In contrast, named arguments offer a more meaningful option, allowing a precise understanding of the data each argument represents. The basic syntax of the named parameters is as follows:

Named parameters typically involve using flags ( short or long options i.e ParameterName in the above syntax) to denote specific parameters and then associating values with those flags . This makes it easier for users to remember and provide only the necessary inputs , even if the script has a complex set of options .

3. Bash Special Parameters

Special parameters in Bash are variables that hold specific information, like the script’s name, the number of arguments passed, exit status of the last command , and process IDs . Here is a list of special parameters in Bash:

These special parameters collectively offer insight into the script’s environment and execution outcomes, thereby facilitating the development of more responsive and adaptable Bash scripts .

2 Practical Cases of Using Bash Parameters

Bash parameters are valuable when you want to add flexibility and customization to your scripts. Here are 2 practical cases that I am going to discuss below. Don’t forget to run the provided code in your distribution to understand the concept fully.

1. Using Bash Parameters in a Function

Bash parameters in functions are indispensable when creating versatile and interactive scripts. By using parameters, you can dynamically customize the behavior of your functions based on input values. Let’s have a practical example that demonstrates how the function works with Bash parameters.

Suppose you need a function to perform arithmetic addition operations . You want to pass two numbers as parameters to the function. You can use the following code to accomplish the task:

Here, $1 and $2 bother are bash parameters. Now if you want to run the bash scrip by the following command, you will get an output as given below.

Using Bash Parameters in a Function

2. Creating Bash Alias with Parameters

In Bash , aliases don’t support parameters, yet you can work around this by crafting functions that can process command – line arguments. These functions can subsequently be employed as aliases within your Linux environment . To illustrate, Let’s have a look at the following command:

The given alias configuration establishes an alias labeled lsdir , which accepts an argument represented by ( $1 ) denoting the directory that we want to list. When engaging this alias , you can provide the desired directory as an argument during its invocation. For instance:

Creating Bash Alias with Parameters

In conclusion, the bash parameter is an effective way to communicate and pass the required argument to the bash script. In this article, I have provided an overall understanding of what is bash parameters. I have also discussed the different practical cases to use and manipulate the bash parameter in your script. However, if you have any questions or queries relevant to this article, don’t forget to comment below. Thank you!

People Also Ask

How to assign bash parameters.

In Bash, parameters are assigned using special variables. The most common ones are “$1” for the first parameter, “$2” for the second, and so on. To assign a value to a variable, you use the “=” operator without spaces. For example:

In this script, the values of the first and second parameters passed to the script are assigned to variables first_param and second_param , respectively. The echo statements then print out these assigned values.

How to pass parameters to bash command?

To pass parameters to a Bash command , simply provide the parameters after the command in the command line. For example command parameter1 parameter2 parameter3 . Replace the command with the actual command you’re running, and replace parameter1 , parameter2 , and parameter3 with the specific parameters you want to pass to the command.

What is $0, $? and $# in shell scripting?

In shell scripting, $0 represents the script’s name or the current shell command, $? stores the exit status of the last executed command, and $# indicates the count of arguments passed to a script or function.

What is $$ variable in bash?

In Bash scripting, the $$ variable represents the process ID ( PID ) of the currently running script or shell. It provides a unique identifier for the specific instance of the script or shell session.

What is $* in shell script?

Related Articles

  • How to Pass All Parameters in Bash Scripts? [6 Cases]
  • How to Use Positional Parameters in Bash Script? [2 Examples]
  • Parsing Parameters in Bash Scripts [5 Examples]
  • 4 Methods to Pass Named Parameters in a Bash Script
  • What is $0 in Bash Script? [4 Practical Examples]
  • Difference Between $$ Vs $ in Bash Scripting [With Examples]
  • How to Use Alias with Parameters in Bash Scripting? [6 Examples]
  • How to Use Bash Function with Parameters? [6 Examples]

<< Go Back to 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.

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

docker run (docker container run)

Create and run a new container from an image

The following commands are equivalent and redirect here:

  • docker container run

Description

The docker run command runs a command in a new container, pulling the image if needed and starting the container.

You can restart a stopped container with all its previous changes intact using docker start . Use docker ps -a to view a list of all containers, including those that are stopped.

Assign name (--name)

The --name flag lets you specify a custom identifier for a container. The following example runs a container named test using the nginx:alpine image in detached mode .

You can reference the container by name with other commands. For example, the following commands stop and remove a container named test :

If you don't specify a custom name using the --name flag, the daemon assigns a randomly generated name, such as vibrant_cannon , to the container. Using a custom-defined name provides the benefit of having an easy-to-remember ID for a container.

Moreover, if you connect the container to a user-defined bridge network, other containers on the same network can refer to the container by name via DNS.

Capture container ID (--cidfile)

To help with automation, you can have Docker write the container ID out to a file of your choosing. This is similar to how some programs might write out their process ID to a file (you might've seen them as PID files):

This creates a container and prints test to the console. The cidfile flag makes Docker attempt to create a new file and write the container ID to it. If the file exists already, Docker returns an error. Docker closes this file when docker run exits.

PID settings (--pid)

By default, all containers have the PID namespace enabled.

PID namespace provides separation of processes. The PID Namespace removes the view of the system processes, and allows process ids to be reused including PID 1.

In certain cases you want your container to share the host's process namespace, allowing processes within the container to see all of the processes on the system. For example, you could build a container with debugging tools like strace or gdb , but want to use these tools when debugging processes within the container.

Example: run htop inside a container

To run htop in a container that shares the process namespac of the host:

Run an alpine container with the --pid=host option:

Install htop in the container:

Invoke the htop command.

Example, join another container's PID namespace

Joining another container's PID namespace can be useful for debugging that container.

Start a container running a Redis server:

Run an Alpine container that attaches the --pid namespace to the my-nginx container:

Install strace in the Alpine container:

Attach to process 1, the process ID of the my-nginx container:

UTS settings (--uts)

The UTS namespace is for setting the hostname and the domain that's visible to running processes in that namespace. By default, all containers, including those with --network=host , have their own UTS namespace. Setting --uts to host results in the container using the same UTS namespace as the host.

Note Docker disallows combining the --hostname and --domainname flags with --uts=host . This is to prevent containers running in the host's UTS namespace from attempting to change the hosts' configuration.

You may wish to share the UTS namespace with the host if you would like the hostname of the container to change as the hostname of the host changes. A more advanced use case would be changing the host's hostname from a container.

IPC settings (--ipc)

The --ipc flag accepts the following values:

If not specified, daemon default is used, which can either be "private" or "shareable" , depending on the daemon version and configuration.

System V interprocess communication (IPC) namespaces provide separation of named shared memory segments, semaphores and message queues.

Shared memory segments are used to accelerate inter-process communication at memory speed, rather than through pipes or through the network stack. Shared memory is commonly used by databases and custom-built (typically C/OpenMPI, C++/using boost libraries) high performance applications for scientific computing and financial services industries. If these types of applications are broken into multiple containers, you might need to share the IPC mechanisms of the containers, using "shareable" mode for the main (i.e. "donor") container, and "container:<donor-name-or-ID>" for other containers.

Full container capabilities (--privileged)

The following example doesn't work, because by default, Docker drops most potentially dangerous kernel capabilities, including CAP_SYS_ADMIN (which is required to mount filesystems).

It works when you add the --privileged flag:

The --privileged flag gives all capabilities to the container, and it also lifts all the limitations enforced by the device cgroup controller. In other words, the container can then do almost everything that the host can do. This flag exists to allow special use-cases, like running Docker within Docker.

Set working directory (-w, --workdir)

The -w option runs the command executed inside the directory specified, in this example, /path/to/dir/ . If the path doesn't exist, Docker creates it inside the container.

Set storage driver options per container (--storage-opt)

This (size) constraints the container filesystem size to 120G at creation time. This option is only available for the btrfs , overlay2 , windowsfilter , and zfs storage drivers.

For the overlay2 storage driver, the size option is only available if the backing filesystem is xfs and mounted with the pquota mount option. Under these conditions, you can pass any size less than the backing filesystem size.

For the windowsfilter , btrfs , and zfs storage drivers, you cannot pass a size less than the Default BaseFS Size.

Mount tmpfs (--tmpfs)

The --tmpfs flag lets you create a tmpfs mount.

The options that you can pass to --tmpfs are identical to the Linux mount -t tmpfs -o command. The following example mounts an empty tmpfs into the container with the rw , noexec , nosuid , size=65536k options.

For more information, see tmpfs mounts .

Mount volume (-v)

The example above mounts the current directory into the container at the same path using the -v flag, sets it as the working directory, and then runs the pwd command inside the container.

As of Docker Engine version 23, you can use relative paths on the host.

The example above mounts the content directory in the current directory into the container at the /content path using the -v flag, sets it as the working directory, and then runs the pwd command inside the container.

When the host directory of a bind-mounted volume doesn't exist, Docker automatically creates this directory on the host for you. In the example above, Docker creates the /doesnt/exist folder before starting your container.

Mount volume read-only (--read-only)

You can use volumes in combination with the --read-only flag to control where a container writes files. The --read-only flag mounts the container's root filesystem as read only prohibiting writes to locations other than the specified volumes for the container.

By bind-mounting the Docker Unix socket and statically linked Docker binary (refer to get the Linux binary ), you give the container the full access to create and manipulate the host's Docker daemon.

On Windows, you must specify the paths using Windows-style path semantics.

The following examples fails when using Windows-based containers, as the destination of a volume or bind mount inside the container must be one of: a non-existing or empty directory; or a drive other than C: . Further, the source of a bind mount must be a local directory, not a file.

For in-depth information about volumes, refer to manage data in containers

Add bind mounts or volumes using the --mount flag

The --mount flag allows you to mount volumes, host-directories, and tmpfs mounts in a container.

The --mount flag supports most options supported by the -v or the --volume flag, but uses a different syntax. For in-depth information on the --mount flag, and a comparison between --volume and --mount , refer to Bind mounts .

Even though there is no plan to deprecate --volume , usage of --mount is recommended.

Publish or expose port (-p, --expose)

This binds port 8080 of the container to TCP port 80 on 127.0.0.1 of the host. You can also specify udp and sctp ports. The Networking overview page explains in detail how to publish ports with Docker.

Note If you don't specify an IP address (i.e., -p 80:80 instead of -p 127.0.0.1:80:80 ) when publishing a container's ports, Docker publishes the port on all interfaces (address 0.0.0.0 ) by default. These ports are externally accessible. This also applies if you configured UFW to block this specific port, as Docker manages its own iptables rules. Read more

This exposes port 80 of the container without publishing the port to the host system's interfaces.

Publish all exposed ports (-P, --publish-all)

The -P , or --publish-all , flag publishes all the exposed ports to the host. Docker binds each exposed port to a random port on the host.

The -P flag only publishes port numbers that are explicitly flagged as exposed, either using the Dockerfile EXPOSE instruction or the --expose flag for the docker run command.

The range of ports are within an ephemeral port range defined by /proc/sys/net/ipv4/ip_local_port_range . Use the -p flag to explicitly map a single port or range of ports.

Set the pull policy (--pull)

Use the --pull flag to set the image pull policy when creating (and running) the container.

The --pull flag can take one of these values:

When creating (and running) a container from an image, the daemon checks if the image exists in the local image cache. If the image is missing, an error is returned to the CLI, allowing it to initiate a pull.

The default ( missing ) is to only pull the image if it's not present in the daemon's image cache. This default allows you to run images that only exist locally (for example, images you built from a Dockerfile, but that have not been pushed to a registry), and reduces networking.

The always option always initiates a pull before creating the container. This option makes sure the image is up-to-date, and prevents you from using outdated images, but may not be suitable in situations where you want to test a locally built image before pushing (as pulling the image overwrites the existing image in the image cache).

The never option disables (implicit) pulling images when creating containers, and only uses images that are available in the image cache. If the specified image is not found, an error is produced, and the container is not created. This option is useful in situations where networking is not available, or to prevent images from being pulled implicitly when creating containers.

The following example shows docker run with the --pull=never option set, which produces en error as the image is missing in the image-cache:

Set environment variables (-e, --env, --env-file)

Use the -e , --env , and --env-file flags to set simple (non-array) environment variables in the container you're running, or overwrite variables defined in the Dockerfile of the image you're running.

You can define the variable and its value when running the container:

You can also use variables exported to your local environment:

When running the command, the Docker CLI client checks the value the variable has in your local environment and passes it to the container. If no = is provided and that variable isn't exported in your local environment, the variable is unset in the container.

You can also load the environment variables from a file. This file should use the syntax <variable>=value (which sets the variable to the given value) or <variable> (which takes the value from the local environment), and # for comments. Lines beginning with # are treated as line comments and are ignored, whereas a # appearing anywhere else in a line is treated as part of the variable value.

Set metadata on container (-l, --label, --label-file)

A label is a key=value pair that applies metadata to a container. To label a container with two labels:

The my-label key doesn't specify a value so the label defaults to an empty string ( "" ). To add multiple labels, repeat the label flag ( -l or --label ).

The key=value must be unique to avoid overwriting the label value. If you specify labels with identical keys but different values, each subsequent value overwrites the previous. Docker uses the last key=value you supply.

Use the --label-file flag to load multiple labels from a file. Delimit each label in the file with an EOL mark. The example below loads labels from a labels file in the current directory:

The label-file format is similar to the format for loading environment variables. (Unlike environment variables, labels are not visible to processes running inside a container.) The following example shows a label-file format:

You can load multiple label-files by supplying multiple --label-file flags.

For additional information on working with labels, see Labels .

Connect a container to a network (--network)

To start a container and connect it to a network, use the --network option.

The following commands create a network named my-net and adds a busybox container to the my-net network.

You can also choose the IP addresses for the container with --ip and --ip6 flags when you start the container on a user-defined network. To assign a static IP to containers, you must specify subnet block for the network.

If you want to add a running container to a network use the docker network connect subcommand.

You can connect multiple containers to the same network. Once connected, the containers can communicate using only another container's IP address or name. For overlay networks or custom plugins that support multi-host connectivity, containers connected to the same multi-host network but launched from different Engines can also communicate in this way.

Note The default bridge network only allow containers to communicate with each other using internal IP addresses. User-created bridge networks provide DNS resolution between containers using container names.

You can disconnect a container from a network using the docker network disconnect command.

For more information on connecting a container to a network when using the run command, see the " Docker network overview " .

Mount volumes from container (--volumes-from)

The --volumes-from flag mounts all the defined volumes from the referenced containers. You can specify more than one container by repetitions of the --volumes-from argument. The container ID may be optionally suffixed with :ro or :rw to mount the volumes in read-only or read-write mode, respectively. By default, Docker mounts the volumes in the same mode (read write or read only) as the reference container.

Labeling systems like SELinux require placing proper labels on volume content mounted into a container. Without a label, the security system might prevent the processes running inside the container from using the content. By default, Docker does not change the labels set by the OS.

To change the label in the container context, you can add either of two suffixes :z or :Z to the volume mount. These suffixes tell Docker to relabel file objects on the shared volumes. The z option tells Docker that two containers share the volume content. As a result, Docker labels the content with a shared content label. Shared volume labels allow all containers to read/write content. The Z option tells Docker to label the content with a private unshared label. Only the current container can use a private volume.

Detached mode (-d, --detach)

The --detach (or -d ) flag starts a container as a background process that doesn't occupy your terminal window. By design, containers started in detached mode exit when the root process used to run the container exits, unless you also specify the --rm option. If you use -d with --rm , the container is removed when it exits or when the daemon exits, whichever happens first.

Don't pass a service x start command to a detached container. For example, this command attempts to start the nginx service.

This succeeds in starting the nginx service inside the container. However, it fails the detached container paradigm in that, the root process ( service nginx start ) returns and the detached container stops as designed. As a result, the nginx service starts but can't be used. Instead, to start a process such as the nginx web server do the following:

To do input/output with a detached container use network connections or shared volumes. These are required because the container is no longer listening to the command line where docker run was run.

Override the detach sequence (--detach-keys)

Use the --detach-keys option to override the Docker key sequence for detach. This is useful if the Docker default sequence conflicts with key sequence you use for other applications. There are two ways to define your own detach key sequence, as a per-container override or as a configuration property on your entire configuration.

To override the sequence for an individual container, use the --detach-keys="<sequence>" flag with the docker attach command. The format of the <sequence> is either a letter [a-Z], or the ctrl- combined with any of the following:

  • a-z (a single lowercase alpha character )
  • @ (at sign)
  • [ (left bracket)
  • \\ (two backward slashes)
  • _ (underscore)

These a , ctrl-a , X , or ctrl-\\ values are all examples of valid key sequences. To configure a different configuration default key sequence for all containers, see Configuration file section .

Add host device to container (--device)

It's often necessary to directly expose devices to a container. The --device option enables that. For example, adding a specific block storage device or loop device or audio device to an otherwise unprivileged container (without the --privileged flag) and have the application directly access it.

By default, the container is able to read , write and mknod these devices. This can be overridden using a third :rwm set of options to each --device flag. If the container is running in privileged mode, then Docker ignores the specified permissions.

Note The --device option cannot be safely used with ephemeral devices. You shouldn't add block devices that may be removed to untrusted containers with --device .

For Windows, the format of the string passed to the --device option is in the form of --device=<IdType>/<Id> . Beginning with Windows Server 2019 and Windows 10 October 2018 Update, Windows only supports an IdType of class and the Id as a device interface class GUID . Refer to the table defined in the Windows container docs for a list of container-supported device interface class GUIDs.

If you specify this option for a process-isolated Windows container, Docker makes all devices that implement the requested device interface class GUID available in the container. For example, the command below makes all COM ports on the host visible in the container.

Note The --device option is only supported on process-isolated Windows containers, and produces an error if the container isolation is hyperv .

CDI devices

Note This is experimental feature and as such doesn't represent a stable API.

Container Device Interface (CDI) is a standardized mechanism for container runtimes to create containers which are able to interact with third party devices.

With CDI, device configurations are defined using a JSON file. In addition to enabling the container to interact with the device node, it also lets you specify additional configuration for the device, such as kernel modules, host libraries, and environment variables.

You can reference a CDI device with the --device flag using the fully-qualified name of the device, as shown in the following example:

This starts an ubuntu container with access to the specified CDI device, vendor.com/class=device-name , assuming that:

  • A valid CDI specification (JSON file) for the requested device is available on the system running the daemon, in one of the configured CDI specification directories.
  • The CDI feature has been enabled on the daemon side, see Enable CDI devices .

Attach to STDIN/STDOUT/STDERR (-a, --attach)

The --attach (or -a ) flag tells docker run to bind to the container's STDIN , STDOUT or STDERR . This makes it possible to manipulate the output and input as needed. You can specify to which of the three standard streams ( STDIN , STDOUT , STDERR ) you'd like to connect instead, as in:

The following example pipes data into a container and prints the container's ID by attaching only to the container's STDIN .

The following example doesn't print anything to the console unless there's an error because output is only attached to the STDERR of the container. The container's logs still store what's written to STDERR and STDOUT .

The following example shows a way of using --attach to pipe a file into a container. The command prints the container's ID after the build completes and you can retrieve the build logs using docker logs . This is useful if you need to pipe a file or something else into a container and retrieve the container's ID once the container has finished running.

Note A process running as PID 1 inside a container is treated specially by Linux: it ignores any signal with the default action. So, the process doesn't terminate on SIGINT or SIGTERM unless it's coded to do so.

See also the docker cp command .

Keep STDIN open (-i, --interactive)

The --interactive (or -i ) flag keeps the container's STDIN open, and lets you send input to the container through standard input.

The -i flag is most often used together with the --tty flag to bind the I/O streams of the container to a pseudo terminal, creating an interactive terminal session for the container. See Allocate a pseudo-TTY for more examples.

Using the -i flag on its own allows for composition, such as piping input to containers:

Specify an init process

You can use the --init flag to indicate that an init process should be used as the PID 1 in the container. Specifying an init process ensures the usual responsibilities of an init system, such as reaping zombie processes, are performed inside the created container.

The default init process used is the first docker-init executable found in the system path of the Docker daemon process. This docker-init binary, included in the default installation, is backed by tini .

Allocate a pseudo-TTY (-t, --tty)

The --tty (or -t ) flag attaches a pseudo-TTY to the container, connecting your terminal to the I/O streams of the container. Allocating a pseudo-TTY to the container means that you get access to input and output feature that TTY devices provide.

For example, the following command runs the passwd command in a debian container, to set a new password for the root user.

If you run this command with only the -i flag (which lets you send text to STDIN of the container), the passwd prompt displays the password in plain text. However, if you try the same thing but also adding the -t flag, the password is hidden:

This is because passwd can suppress the output of characters to the terminal using the echo-off TTY feature.

You can use the -t flag without -i flag. This still allocates a pseudo-TTY to the container, but with no way of writing to STDIN . The only time this might be useful is if the output of the container requires a TTY environment.

Specify custom cgroups

Using the --cgroup-parent flag, you can pass a specific cgroup to run a container in. This allows you to create and manage cgroups on their own. You can define custom resources for those cgroups and put containers under a common parent group.

Using dynamically created devices (--device-cgroup-rule)

Docker assigns devices available to a container at creation time. The assigned devices are added to the cgroup.allow file and created into the container when it runs. This poses a problem when you need to add a new device to running container.

One solution is to add a more permissive rule to a container allowing it access to a wider range of devices. For example, supposing the container needs access to a character device with major 42 and any number of minor numbers (added as new devices appear), add the following rule:

Then, a user could ask udev to execute a script that would docker exec my-container mknod newDevX c 42 <minor> the required device when it is added.

Note : You still need to explicitly add initially present devices to the docker run / docker create command.

Access an NVIDIA GPU

The --gpus flag allows you to access NVIDIA GPU resources. First you need to install the nvidia-container-runtime .

Note You can also specify a GPU as a CDI device with the --device flag, see CDI devices .

Read Specify a container's resources for more information.

To use --gpus , specify which GPUs (or all) to use. If you provide no value, Docker uses all available GPUs. The example below exposes all available GPUs.

Use the device option to specify GPUs. The example below exposes a specific GPU.

The example below exposes the first and third GPUs.

Restart policies (--restart)

Use the --restart flag to specify a container's restart policy . A restart policy controls whether the Docker daemon restarts a container after exit. Docker supports the following restart policies:

This runs the redis container with a restart policy of always . If the container exits, Docker restarts it.

When a restart policy is active on a container, it shows as either Up or Restarting in docker ps . It can also be useful to use docker events to see the restart policy in effect.

An increasing delay (double the previous delay, starting at 100 milliseconds) is added before each restart to prevent flooding the server. This means the daemon waits for 100 ms, then 200 ms, 400, 800, 1600, and so on until either the on-failure limit, the maximum delay of 1 minute is hit, or when you docker stop or docker rm -f the container.

If a container is successfully restarted (the container is started and runs for at least 10 seconds), the delay is reset to its default value of 100 ms.

Specify a limit for restart attempts

You can specify the maximum amount of times Docker attempts to restart the container when using the on-failure policy. By default, Docker never stops attempting to restart the container.

The following example runs the redis container with a restart policy of on-failure and a maximum restart count of 10.

If the redis container exits with a non-zero exit status more than 10 times in a row, Docker stops trying to restart the container. Providing a maximum restart limit is only valid for the on-failure policy.

Inspect container restarts

The number of (attempted) restarts for a container can be obtained using the docker inspect command. For example, to get the number of restarts for container "my-container";

Or, to get the last time the container was (re)started;

Combining --restart (restart policy) with the --rm (clean up) flag results in an error. On container restart, attached clients are disconnected.

Clean up (--rm)

By default, a container's file system persists even after the container exits. This makes debugging a lot easier, since you can inspect the container's final state and you retain all your data.

If you are running short-term foreground processes, these container file systems can start to pile up. If you'd like Docker to automatically clean up the container and remove the file system when the container exits, use the --rm flag:

Note If you set the --rm flag, Docker also removes the anonymous volumes associated with the container when the container is removed. This is similar to running docker rm -v my-container . Only volumes that are specified without a name are removed. For example, when running the following command, volume /foo is removed, but not /bar : copying = false, 2000);"> $ docker run --rm -v /foo -v awesome:/bar busybox top Volumes inherited via --volumes-from are removed with the same logic: if the original volume was specified with a name it isn't removed.

Add entries to container hosts file (--add-host)

You can add other hosts into a container's /etc/hosts file by using one or more --add-host flags. This example adds a static address for a host named my-hostname :

You can wrap an IPv6 address in square brackets:

The --add-host flag supports a special host-gateway value that resolves to the internal IP address of the host. This is useful when you want containers to connect to services running on the host machine.

It's conventional to use host.docker.internal as the hostname referring to host-gateway . Docker Desktop automatically resolves this hostname, see Explore networking features .

The following example shows how the special host-gateway value works. The example runs an HTTP server that serves a file from host to container over the host.docker.internal hostname, which resolves to the host's internal IP.

The --add-host flag also accepts a : separator, for example:

Logging drivers (--log-driver)

The container can have a different logging driver than the Docker daemon. Use the --log-driver=<DRIVER> with the docker run command to configure the container's logging driver.

To learn about the supported logging drivers and how to use them, refer to Configure logging drivers .

To disable logging for a container, set the --log-driver flag to none :

Set ulimits in container (--ulimit)

Since setting ulimit settings in a container requires extra privileges not available in the default container, you can set these using the --ulimit flag. Specify --ulimit with a soft and hard limit in the format <type>=<soft limit>[:<hard limit>] . For example:

Note If you don't provide a hard limit value, Docker uses the soft limit value for both values. If you don't provide any values, they are inherited from the default ulimits set on the daemon.
Note The as option is deprecated. In other words, the following script is not supported: copying = false, 2000);"> $ docker run -it --ulimit as = 1024 fedora /bin/bash

Docker sends the values to the appropriate OS syscall and doesn't perform any byte conversion. Take this into account when setting the values.

For nproc usage

Be careful setting nproc with the ulimit flag as Linux uses nproc to set the maximum number of processes available to a user, not to a container. For example, start four containers with daemon user:

The 4th container fails and reports a "[8] System error: resource temporarily unavailable" error. This fails because the caller set nproc=3 resulting in the first three containers using up the three processes quota set for the daemon user.

Stop container with signal (--stop-signal)

The --stop-signal flag sends the system call signal to the container to exit. This signal can be a signal name in the format SIG<NAME> , for instance SIGKILL , or an unsigned number that matches a position in the kernel's syscall table, for instance 9 .

The default value is defined by STOPSIGNAL in the image, or SIGTERM if the image has no STOPSIGNAL defined.

Optional security options (--security-opt)

The --security-opt flag lets you override the default labeling scheme for a container. Specifying the level in the following command allows you to share the same content between containers.

Note Automatic translation of MLS labels isn't supported.

To disable the security labeling for a container entirely, you can use label=disable :

If you want a tighter security policy on the processes within a container, you can specify a custom type label. The following example runs a container that's only allowed to listen on Apache ports:

Note You would have to write policy defining a svirt_apache_t type.

To prevent your container processes from gaining additional privileges, you can use the following command:

This means that commands that raise privileges such as su or sudo no longer work. It also causes any seccomp filters to be applied later, after privileges have been dropped which may mean you can have a more restrictive set of filters. For more details, see the kernel documentation .

On Windows, you can use the --security-opt flag to specify the credentialspec option. The credentialspec must be in the format file://spec.txt or registry://keyname .

Stop container with timeout (--stop-timeout)

The --stop-timeout flag sets the number of seconds to wait for the container to stop after sending the pre-defined (see --stop-signal ) system call signal. If the container does not exit after the timeout elapses, it's forcibly killed with a SIGKILL signal.

If you set --stop-timeout to -1 , no timeout is applied, and the daemon waits indefinitely for the container to exit.

The Daemon determines the default, and is 10 seconds for Linux containers, and 30 seconds for Windows containers.

Specify isolation technology for container (--isolation)

This option is useful in situations where you are running Docker containers on Windows. The --isolation=<value> option sets a container's isolation technology. On Linux, the only supported is the default option which uses Linux namespaces. These two commands are equivalent on Linux:

On Windows, --isolation can take one of these values:

The default isolation on Windows server operating systems is process , and hyperv on Windows client operating systems, such as Windows 10. Process isolation has better performance, but requires that the image and host use the same kernel version.

On Windows server, assuming the default configuration, these commands are equivalent and result in process isolation:

If you have set the --exec-opt isolation=hyperv option on the Docker daemon , or are running against a Windows client-based daemon, these commands are equivalent and result in hyperv isolation:

Specify hard limits on memory available to containers (-m, --memory)

These parameters always set an upper limit on the memory available to the container. Linux sets this on the cgroup and applications in a container can query it at /sys/fs/cgroup/memory/memory.limit_in_bytes .

On Windows, this affects containers differently depending on what type of isolation you use.

With process isolation, Windows reports the full memory of the host system, not the limit to applications running inside the container

With hyperv isolation, Windows creates a utility VM that is big enough to hold the memory limit, plus the minimal OS needed to host the container. That size is reported as "Total Physical Memory."

Configure namespaced kernel parameters (sysctls) at runtime (--sysctl)

The --sysctl sets namespaced kernel parameters (sysctls) in the container. For example, to turn on IP forwarding in the containers network namespace, run this command:

Note Not all sysctls are namespaced. Docker does not support changing sysctls inside of a container that also modify the host system. As the kernel evolves we expect to see more sysctls become namespaced.

Currently supported sysctls

IPC Namespace:

  • kernel.msgmax , kernel.msgmnb , kernel.msgmni , kernel.sem , kernel.shmall , kernel.shmmax , kernel.shmmni , kernel.shm_rmid_forced .
  • Sysctls beginning with fs.mqueue.*
  • If you use the --ipc=host option these sysctls are not allowed.

Network Namespace:

  • Sysctls beginning with net.*
  • If you use the --network=host option using these sysctls are not allowed.
  • Developing Applications with Oracle Visual Builder
  • Develop Applications
  • Work with Fragments
  • Pass Data Between a Fragment and Its Parent Container

Set the Binding Type for Variables in Dynamic Components

When a variable is used as an input parameter in a dynamic component in a fragment, you can assign a subtype to the variable to indicate how the input parameter is to be used.

Subtypes are typically used to configure how variables are displayed in the Properties pane, but there are some special subtypes that are used to set the binding type for variables in fragments, and do not affect how the variables are displayed in the Properties pane.

Specifying a binding type provides information that Visual Builder requires to generate suitable metadata and expressions. The subtype you select should be based on the type of component where the variable is used. For example, if the variable will be used in a Dynamic Form Template, you would set the subtype to Dynamic Field.

  • Open the fragment's Variables editor.
  • Select the variable or constant.
  • Open the Design Time tab in the Properties pane.

IMAGES

  1. How to use Variables in Bash Programming

    bash assign parameter to variable

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

    bash assign parameter to variable

  3. How to use Variables in Bash

    bash assign parameter to variable

  4. How to Assign Variable in Bash

    bash assign parameter to variable

  5. How to use Variables in Bash

    bash assign parameter to variable

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

    bash assign parameter to variable

VIDEO

  1. Manage Tables in KNIME Rename, Sort, Filter, and Assign Variable Types

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

  3. Imp Points To Develop Real-Time Bash Shell Scripts

  4. Lecture 18

  5. ENSONIQ DP4

  6. Geometry Bash 2 Trailer

COMMENTS

  1. How to Work with Variables in Bash

    Home Linux How to Work with Variables in Bash By Dave McKay Updated Aug 12, 2023 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 Readers like you help support How-To Geek.

  2. Bash: How to set a variable from argument, and with a default value

    1 I found my answer to what the colon means: wiki.bash-hackers.org/syntax/pe#use_a_default_value - Steven Lu Apr 18, 2013 at 5:07 4 Embrace the language. Not all languages have the same idioms. DIR=$ {1:-.} is a perfectly natural way to express this logic in any POSIX-compatible shell. - chepner Apr 18, 2013 at 12:26 1

  3. bash set variable from commandline argument

    1 Answer Sorted by: 34 The correct assignment is simply the following, with no spaces on either side of the equal sign: var1=$1 The command set var1 = $1 actually does the following: Sets the value of $1 to "var1" Sets the value of $2 to "=" Sets the value of $3 to the original first parameter $1. Share Improve this answer Follow

  4. How to Pass Arguments to a Bash Shell Script

    The first bash argument (also known as a positional parameter) can be accessed within your bash script using the $1 variable. So in the count_lines.sh script, you can replace the filename variable with $1 as follows: #!/bin/bash nlines=$ (wc -l < $1) echo "There are $nlines lines in $1"

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

    How to Assign Default Value to a Variable Using Bash Last updated: December 3, 2023 Written by: Jimmy Azar Scripting bash echo 1. Overview 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

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

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

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

    Bash Variable Basics: Setting and Using Variables. In Bash, setting a variable is a straightforward process. It's done using the '=' operator with no spaces between the variable name, the '=' operator, and the value you want to assign to the variable.

  9. bash

    1 Answer Sorted by: 3 Variable does not exist if it's not set. For example, unset var echo $ {var?"this is not set"} -bash: var: this is not set The shell displays an error message if var is not set. The echo is not executed.

  10. bash

    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. $ {parameter:-word} If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

  11. How to Use Command Line Arguments in a Bash Script

    sh users-shift-operator.sh john matt bill 'joe wicks' carol. The output will be the same as before: Username - 1: john Username - 2: matt Username - 3: bill Username - 4: joe wicks Username - 5: carol. In this example, we're shifting the positional parameter in each iteration by one until we reach the end of the input.

  12. Parameters in Bash Scripting

    Positional parameters in Bash are a set of variables that capture and retain values passed as arguments when a script or command is invoked. The foremost among these parameters is $0, which signifies the name of the script or command itself. It is essential for self-reference. Accompanying this is a sequence of $1, $2, $3, and so on ...

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

  14. Using Arguments in Bash Scripts

    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.

  15. Assign values to shell variables

    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 assigned the null string. How Do I Display The Variable Value? You can display the value of a variable with echo $varName or echo $ {varName} : echo "$varName" OR

  16. How do I assign a value to a BASH variable if that variable is null

    2 Answers Sorted by: 98 Either of these expansions might be what you're looking for, depending on when exactly you want to do the assignment: Omitting the colon results in a test only for a parameter that is unset. [...] $ {parameter:-word} If parameter is unset or null, the expansion of word is substituted.

  17. docker run

    Aliases. The following commands are equivalent and redirect here: docker container run; docker run; Description. The docker run command runs a command in a new container, pulling the image if needed and starting the container.. You can restart a stopped container with all its previous changes intact using docker start.Use docker ps -a to view a list of all containers, including those that are ...

  18. How to build a conditional assignment in bash?

    8 Answers Sorted by: 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. ;] Share Improve this answer

  19. Set the Binding Type for Variables in Dynamic Components

    To assign a subtype to a fragment variable: Open the fragment's Variables editor. Select the variable or constant. Open the Design Time tab in the Properties pane. Select the subtype for the fragment variable. Here are the subtypes that are used to set a binding type for a variable:

  20. Bash function assign value to passed parameter

    Bash function assign value to passed parameter Ask Question Asked 7 years, 3 months ago Modified 7 years, 3 months ago Viewed 4k times 1 I've got the following situation: I'm writing a script that will read its parameters either from a config file (if exists and parameter present) or asks the user to input said parameter if it's not present.

  21. How do I set a variable to the output of a command in Bash?

    How do I set a variable to the output of a command in Bash? Ask Question Asked 13 years, 1 month ago Modified 2 months ago Viewed 2.8m times 2399 I have a pretty simple script that is something like the following: #!/bin/bash VAR1="$1" MOREF='sudo run command against $VAR1 | grep name | cut -c7-' echo $MOREF

  22. How can we run a command stored in a variable?

    How can we run a command stored in a variable? Ask Question Asked 5 years, 9 months ago Modified 2 months ago Viewed 280k times 184 $ ls -l /tmp/test/my\ dir/ total 0 I was wondering why the following ways to run the above command fail or succeed? $ abc='ls -l "/tmp/test/my dir"' $ $abc ls: cannot access '"/tmp/test/my': No such file or directory