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,





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"


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 in a terminal window

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


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

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

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

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


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

chmod +x in a terminal window

Type the following to run the script:

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

#!/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

chmod +x 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:

./ /dev

./ /etc

./ /bin

./ /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, :

#!/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

fig13 in a terminal window

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

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

#!/bin/bashfirst_var=alphasecond_var=bravo# check their valuesecho "$0: first_var=$first_var, second_var=$second_var"export first_varexport second_var./ 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 . When 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 . This is the script that 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

chmod +x in a terminal window

And now, type the following to launch :


./ in a terminal window

This is what the output tells us:

  • prints the values of the variables, which are alpha and bravo.
  • prints the values of the variables (alpha and bravo) as it received them.
  • changes them to charlie and delta.
  • 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"


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.

Stack Exchange Network

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

Q&A for work

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

How can I assign variables from file into a bash script and write a specific loop for it?

I have a file containing n lines and each line has three variables(i.e. words) separated by a comma. I want to write a script in bash which takes each variable and fill a template message such as:

My problem is I don't know how to assign these variables in bash, and how to make a bash script that will generate the message above in a different file names for all the n lines.

  • command-line

satalmaty 's user avatar

  • assigning variables in bash is as simple as poop=35 ... you can do that right on the command line and then echo $poop to view the value... Look into awk and look into for loops to parse your file into variables in your script... you can use redirection ">" to create files with the variable names you parsed. echo "hello" > $poop.txt ... there are plenty of tutorials everywhere on the web on all of these. –  WU-TANG Dec 12, 2020 at 12:54

Assuming a.file contains your data:

$IFS is the character that separates your words

read is a builtin shell function that reads a line of input, split it into words and assigns them to the given variables.

Florian Diesch's user avatar

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged command-line bash scripts ..

  • The Overflow Blog
  • How to convince your CEO it’s worth paying down tech debt
  • Even LLMs need education—quality data makes LLMs overperform
  • Featured on Meta
  • Goodbye Gunnar Hjalmarsson 1958.10.06 - 2023.12.20
  • AI-generated content is not permitted on Ask Ubuntu

Hot Network Questions

  • Find the heaviest and the second heaviest coins
  • "Uterine Disease" in 1880
  • Is a randomly generated 80-bit password strong enough nowadays?
  • What does it mean "the earth is God's footstool"?
  • Search the deepest depths of an array
  • Why are Republicans more likely to support keeping the filibuster than Democrats in the U.S.?
  • Info about Goddess Rikshakarni
  • How to get the first three letters of today’s day of week?
  • Why is the horizon problem a problem?
  • Is it coincidence that the earth's rotation and revolution are in the same direction?
  • How many distinct colors would tetrachromatic birds have?
  • My colleague took my teaching materials to use as their own. What should I do?
  • Two years after the breakout of Ukraine war, is/how is Russia successful in sustaining its economy (now even growing?) and the war?
  • Are there mutually independent undecidable statements?
  • Do you know about topologies that look like this?
  • Contract a tensor
  • How is called the Chinese language in Taiwan?
  • A word for a man of few, but well thought-out, words
  • Is there a reason why Apple servers did not catch on?
  • What are mild versions of unrequited love?
  • The implication if we discovered that natural abiogenesis is statistically nearly impossible
  • How to simulate d616 on Anydice?
  • Firefox on Ubuntu 22.04 is garbled on HP laptop
  • Will staying longer than planned in Japan cause problems?

bash assign file to variable


Home > Bash Scripting Tutorial > Bash Variables > Variable Declaration and Assignment

Variable Declaration and Assignment

Mohammad Shah Miran

In programming, a variable serves as a placeholder for an unknown value, enabling the user to store the different data and access them whenever needed. During compilation or interpretation , the symbolic names of variables are replaced with their corresponding data locations . This article will mainly focus on the variable declaration and assignment in a Bash Script . So, let’s start.

Key Takeaways

  • Getting familiar with Bash Variables.
  • Learning to declare and assign variables.

Free Downloads

Factors of variable declaration and assignment.

There are multiple factors to be followed to declare a variable and assign data to it. Here I have listed the factors below to understand the process. Check it out.

1. Choosing Appropriate Variable Name

When choosing appropriate variable names for declaration and assignment, it’s essential to follow some guidelines to ensure clarity and readability and to avoid conflicts with other system variables. Here some common guidelines to be followed are listed below:

  • Using descriptive names: Using descriptive names in variable naming conventions involves choosing meaningful and expressive names for variables in your code. This practice improves code readability and makes it easier to grasp the purpose of the code at a glance.
  • Using lowercase letters: It is a good practice to begin variable names with a lowercase letter . This convention is not enforced by the bash language itself, but it is a widely followed practice to improve code readability and maintain consistency . For example name , age , count , etc.
  • Separating words with underscores: Using underscores to separate words in variable names enhances code readability. For example first_name , num_students , etc.
  • Avoid starting with numbers: Variable names should not begin with a number. For instance, 1var is not a valid variable
  • Avoiding special characters : Avoid using special characters , whitespace , or punctuation marks, as they can cause syntax errors or introduce unexpected behavior. For instance, using any special character such as @, $, or # anywhere while declaring a variable is not legal.

2. Declaring the Variable in the Bash Script

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. Assigning the Value to the Variable

When declaring variables for numeric values , simply assign the desired number directly, as in age=30 for an integer or price=12.99 for a floating – point value . For strings , enclose the text in single or double quotes , such as name =’ John ‘ or city =” New York “. Booleans can be represented using 0 and 1 , where 0 indicates false and 1 represents true , like is_valid = 1 .

Arrays are declared by assigning a sequence of values enclosed in parentheses to a variable, e.g., fruits=(“apple” “banana” “orange”) . To create associative arrays ( key-value pairs ), use the declare -A command followed by assigning the elements, like declare -A ages=([“John”]=30 [“Jane”]=25) .

4 Practical Cases of Declaring and Assigning Bash Variable

In this section, I have demonstrated some sample Bash scripts that will help you understand the basic concept of variable declaration and assignment in Bash script . So let’s get into it.

Case 01: Basic Variable Assignment in Bash Script

In my first case , I have shown a basic variable assignment with its output. Here, I have taken a string and an integer variable to show the basic variable assignment mechanism. Follow the given steps to accomplish the task.

Steps to Follow >

❶ At first, launch an Ubuntu terminal .

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

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

❸ Copy the script mentioned below:

The script starts with the shebang line ( #!/bin/bash ), specifying that the script should be executed using the Bash shell . Next, two variables are declared and assigned values using the format variable_name = value . The first variable is name , and it is assigned the string value “ John .” The second variable is age , assigned the numeric value 30 . The script then uses the echo command to print the values of the variables.

❹ Press CTRL+O and ENTER to save the file; CTRL+X to exit.

❺ Use the following command to make the file executable:

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

❻ Run the script by the following command:

Basic Variable Assignment in Bash Script

Case 02: Input From User and Variable Assignment

In Bash , you can take input from the user and store it in variables using the read command . To do so use the following script:

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

Script ( >

The script starts with the shebang line ( #!/bin/bash ) to specify that the Bash shell should be used for executing the script. The read command is then used twice, each with the -p option, to prompt the user for input. Both the name and age variables take the name and age of the user and store them in the name and age variable with the help of the read command . Then the script uses the echo command to print the values of the variable’s name and age , respectively. The $ name and $age syntax are used to access the values stored in the variables and display them in the output.

Now, run the following command into your terminal to execute the bash file.

Input from User and Variable Assignment

Case 03: Variable Assignment Using Positional Parameters

In Bash , you can assign values to variables using positional parameters . Positional parameters are special variables that hold arguments passed to the script when it is executed. They are referenced by their position, starting from $0 for the script name, $1 for the first argument , $2 for the second argument , and so on. To do the same use the below script.

Script ( >

The script starts with the shebang line ( #!/bin/bash ) to specify that the Bash shell should be used for executing the script. The script uses the special variables $1 and $2, which represent the first and second command – line arguments , respectively, and assigns their values to the name and age variables . The $ name and $age syntax are used to access the values stored in the variables and display them using the echo command .

Now, run the following command into your terminal to execute the script.

Variable Assignment Using Positional Parameters

Upon execution of the Bash file , the script takes two command-line arguments, John and 30 , and returns the output Name : John and Age : 30 in the command line.

Case 04:  Environment Variables and Variable Scope

In Bash script , Environment Variables are another type of variable. Those variables are available in the current session and its child processes once you export your own variable in the environment. However, you can access those and scope it to a function. Here’s a sample Bash script code of environment variables and variable scope describing the concept.

Script ( >

The script starts with the shebang line ( #!/bin/bash ) to specify that the Bash shell should be used for executing the script. Then, an environment variable named MY_VARIABLE is assigned the value “ Hello, World! ” using the export command . The script also defines a Bash function called my_function . Inside this function, a local variable named local_var is declared using the local keyword . After defining the function, the script proceeds to print the value of the environment variable MY_VARIABLE , which is accessible throughout the script. Upon calling the my_function , it prints the value of the local variable local_var , demonstrating its local scope .

Finally, run the following command into your terminal to execute the bash file.

Environment Variables and Variable Scope

Upon printing the My_VARIABLE and calling the my_function, the code returns “ Environment Variable: Hello, World ” and “ I am a local variable ” respectively.

In conclusion, variable declaration and assignment is a very straightforward process and does not take any extra effort to declare the variable first, just like the Python programming language . In this article, I have tried to give you a guideline on how to declare and assign variables in a Bash Scripts . I have also provided some practical cases related to this topic. However, if you have any questions or queries regarding this article, feel free to comment below. I will get back to you soon. Thank You!

People Also Ask

Related Articles

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

<< Go Back to Bash Variables | Bash Scripting Tutorial

Mohammad Shah Miran

Mohammad Shah Miran

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

Leave a Comment Cancel reply

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

Chapter 19 Notes

  • Computer Science

docker container run


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 namespace 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 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 ) when publishing a container's ports, Docker publishes the port on all interfaces (address ) 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, , 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.


How to set alias for command in bash script?

Open the Terminal app and then type the following commands:

  • Edit the ~/.bash_aliases or ~/.bashrc (recommended) file using a text editor: $ vi ~/.bash_aliases. …
  • Append your bash alias.
  • For example append: alias update=’sudo yum update’
  • Save and close the file.
  • Activate alias by typing the following source command:

How do you assign a command to an alias?

What you need to do is type the word alias then use the name you wish to use to execute a command followed by “=” sign and quote the command you wish to alias. You can then use “wr” shortcut to go to the webroot directory. The problem with that alias is that it will only be available for your current terminal session.

Which command can be used to set an alias?

The Set-Alias cmdlet creates an alias in the current PowerShell session. The Name parameter specifies the alias’s name, list . The Value parameter specifies the cmdlet that the alias runs. To run the alias, type list on the PowerShell command line.

How to use alias command in shell script?

To create an alias, we need to create a file called bash_profile or bashrc. This file needs to be in the root directory and should be hidden to avoid mishandling of its contents. Inside of this file, we create an alias which is basically a map of commands and the sets of commands/functions to be executed as a shortcut.

How do I add an alias to a command in Linux?

2. Open the . bashrc file

  • Open the .bashrc file with the command:
  • nano ~/.bashrc.
  • # update alias. Below, we’ll add our alias, which looks like this:
  • alias update=’sudo apt-get update && sudo apt-get upgrade -y && sudo snap refresh’ The breakdown is simple:
  • alias SHORTCUT=’COMMAND’ …

Aliases – Bash Scripting

What is an alias command in shell.

An alias replaces a string that invokes a command in the Linux shell with another user-defined string. Aliases are mostly used to replace long commands, improving efficiency and avoiding potential spelling errors.

How to set alias multiple commands?

Aliasing multiple commands

You can combine multiple commands in an alias by separating them with a semicolon, or by using && , which will run the next command only if the previous command succeeds. This will cd to the top-level git directory, check out the main branch, and run git pull .

How do I create an alias for multiple commands in bash?

You can combine multiple commands in an alias by separating them with a semicolon, or by using && , which will run the next command only if the previous command succeeds.

How do I put multiple commands in one command?

There are several simple ways you can combine several commands on a single command line:

  • You can run a series of commands, one after the other: Using a semicolon (;) Using && and ||
  • You can run more than one command concurrently: Using a pipe (|) or a filter with a pipe.

How do I put multiple commands in one command line?

Running Multiple Commands as a Single Job

We can start multiple commands as a single job through three steps: Combining the commands – We can use “;“, “&&“, or “||“ to concatenate our commands, depending on the requirement of conditional logic, for example: cmd1; cmd2 && cmd3 || cmd4.

What is the alias of a Bash script?

The alias keyword in BASH replaces a string with another string. The shorthand command is the string that will be used instead of the string on the right-hand side in the command. Hence the alias keyword acts as an abbreviation for a string which is a set of commands or functions.

How do you define an alias in Bash?

A Bash alias is a method of supplementing or overriding Bash commands with new ones. Bash aliases make it easy for users to customize their experience in a POSIX terminal. They are often defined in $HOME/. bashrc or $HOME/bash_aliases (which must be loaded by $HOME/.

What is an example of a Bash alias?

A Bash alias is essentially nothing more than a keyboard shortcut, an abbreviation, a means of avoiding typing a long command sequence. If, for example, we include alias lm=”ls -l | more” in the ~/. bashrc file, then each lm [1] typed at the command-line will automatically be replaced by a ls -l | more.

Can I use alias in Bash script?

A BASH Alias is a map of commands with the sets of commands or functions that can be used as a shortcut in the command line for a BASH environment. Bash Alias allows to aggregate multiple functions into a single command and also it avoids repetitive or large commands into a simple shortcut command.

How to call a command without alias in Bash?

How to to bypass bash alias

  • Prefix a before bash alias name to avoid calling the alias: alias-name.
  • Use the shell builtin named command: command rm.
  • Try using the full path for the shell command to bypass the alias: /bin/mount.
  • Add a single or double quote to the command to avoid the alias: “rm” filename. OR. ‘rm’ file1.

How do I view alias in Bash?

Just type alias while at the Shell prompt. It should output a list of all currently-active aliases. Or, you can type alias [command] to see what a specific alias is aliased to, as an example, if you wanted to find out what the ls alias was aliased to, you could do alias ls .

How do I call a Bash script?

Run Bash Script using the GUI

  • Open Files and click on the top-right icon.
  • Select Preferences from the list.
  • Click the Behavior tab in the menu. Then, select Ask what to do in the Executable Text Files section.
  • Close the menu and double-click the script file. A prompt appears with several options.

How do I set a variable in Bash?

At its most basic, “set – $VARIABLE” is used to split the value of a bash variable into separate words, using the Internal Field Separator (IFS) as the delimiter. For example, if VARIABLE has the value “a b c”, then running “set – $VARIABLE” would set the positional parameters to “a”, “b”, and “c”.

What is a simple alias?

A simple alias holds simple key property values. The name of the alias can be used in the configuration of the properties of a routing policy or an email destination for the Log Invocation, Monitor Service Level Agreement, Monitor Service Performance, and Throttling Traffic Optimization policies.

What is set in bash script?

set is a command that allows you to enable certain flags in your Bash script to make the script follow certain behaviors and characteristics.

How do you write multiple commands in shell script?

On Windows you can use a single ampersand (&) or two ampersands (&&) to separate multiple commands on one command line. When a single ampersand is used, cmd.exe runs the first command, and then the second command.

How do I run a bash command sequentially?

Running commands in a sequence

To achieve this, all we have to do is place a semicolon symbol (;) in between each command of our sequence. If we wanted for example to echo John , then wait for 2 seconds using the sleep command and then echo Doe , we could chain our three commands like this.

What does exec do in bash?

The exec command in Linux is used to execute a command from the bash itself. This command does not create a new process, it just replaces the bash with the command to be executed. If the exec command is successful, it does not return to the calling process.

What is the difference between exec and command in bash?

Whenever we run any command in a Bash shell, a subshell is created by default, and a new child process is spawned (forked) to execute the command. When using exec, however, the command following exec replaces the current shell. This means no subshell is created and the current process is replaced with this new command.

What does exec $@ mean in bash?

The exec will replace the current process with the process resulting from executing its argument. In short, exec “$@” will run the command given by the command line parameters in such a way that the current process is replaced by it (if the exec is able to execute the command at all).

About The Author

Bernice silva, leave a comment cancel reply.

Your email address will not be published. Required fields are marked *

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


  1. How to Use Variables in Bash Shell Scripts

    bash assign file to variable

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

    bash assign file to variable

  3. How to Assign Variable in Bash

    bash assign file to variable

  4. Bash Assign Output of Shell Command To Variable

    bash assign file to variable

  5. How to use Variables in Bash

    bash assign file to variable

  6. Unix & Linux: Missing File In Bash

    bash assign file to variable


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

  2. Project 1 # Shell scripting

  3. Get Data Into Your BASH Script!

  4. How to create a Bash Script to get User Data on Oracle Linux 9.2

  5. What's "[@]" doing to variable in bash for loop

  6. Functions In Bash


  1. Need to assign the contents of a text file to a variable in a bash

    Ask Question Asked 11 years, 1 month ago Modified 1 year, 9 months ago Viewed 151k times 63 I am very new to making bash scripts, but my goal here is to take a .txt file I have and assign the string of words in the txt file to a variable. I have tried this (no clue if I am on the right track or not). #!/bin/bash FILE="answer.txt"

  2. How to Work with Variables in Bash

    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.

  3. shell script

    1 I am appending data to a file and then use echo "$(tail -n10 newdata.txt)" > newdata.txt; to keep only 10 lines in the newdata.txt file. I want to read this file and store all of its content in a variable so that when I perform {"Value":" "} | jq . to create a JSON file. I will be able to write all 10 values to only one keyword value. I tried

  4. How to Write Bash Variable Contents to a File

    1. Overview Sometimes, when writing scripts in Linux, we may want to write the contents of a Bash variable to a file. In this tutorial, we'll present a few ways to write information stored in Bash variables to a file. 2. Using echo One way we can write variable contents to a file is to use the echo command along with the redirect operator.

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

  6. command line

    I have a file containing n lines and each line has three variables(i.e. words) separated by a comma. I want to write a script in bash which takes each variable and fill a template message such as:

  7. How can I reference a file for variables using Bash?

    How can I reference a file for variables using Bash? Ask Question Asked 12 years, 11 months ago Modified 1 year, 10 months ago Viewed 237k times 186 I want to call a settings file for a variable. How can I do this in Bash? The settings file will define the variables (for example, CONFIG.FILE): production="liveschool_joe" playschool="playschool_joe"

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

  9. How to Write Bash Variable to a File? [3 Effective Methods]

    The image shows that the Bash script has written the var1 variable to the file1.txt file and then printed the content of the file1.txt file on the terminal.. Method 02: Using the "here" String to Write Variable to File. Bash programmer can utilize the here-string to write a variable to file which is a technique to put string and variable value together.

  10. Variable Declaration and Assignment

    The script starts with the shebang line (#!/bin/bash), specifying that the script should be executed using the Bash shell.Next, two variables are declared and assigned values using the format variable_name=value.The first variable is name, and it is assigned the string value "John."The second variable is age, assigned the numeric value 30.The script then uses the echo command to print the ...

  11. Bash Assign Output of Shell Command To Variable

    To assign output of any shell command to variable in bash, use the following command substitution syntax: var =$ ( command-name-here) var =$ ( command-name-here arg1) var =$ (/ path / to /command) var =$ (/ path / to /command arg1 arg2) OR use backticks based syntax as follows to assign output of a Linux or Unix command to a variable: var ...

  12. Bash Script: Set variable example

    In order to call the variable later in the script, we precede it with a dollar sign $. Next, look at the examples below to see more practical examples of setting a variable in a Bash script. Bash Script: Set variable examples. Check out the examples below to see how to set variables within a Bash script.

  13. bash

    bash - Assign file names to a variable in shell - Stack Overflow Assign file names to a variable in shell Ask Question Asked 11 years, 2 months ago Modified 10 years, 1 month ago Viewed 25k times 3 I'm trying to write a script that does something a bit more sophisticated than what I'm going to show you, but I know that the problem is in this part.

  14. bash

    1 Answer Sorted by: 10 Globbing only occurs in list contexts, so you'd need to assign to an array variable. With ksh93, bash, zsh, mksh or yash: the_files=(~/downloads/stack-*-linux-x86_64-static.tar.gz) Or in sh: set -- ~/downloads/stack-*-linux-x86_64-static.tar.gz to assign to $1, $2 ...

  15. Chapter 19 Notes (docx)

    Beginning a Shell Script: Creating a script file: -Specify the shell type in the first line of the file o For bash shell script, should start with this format: #!/bin/bash -Commands entered into the file are processed in the order they appear (top to bottom) -Lines with pound symbol (#) (except the first line) are comments and aren't interpreted by the shell.

  16. docker run

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

  17. Assigning a variable a filename in bash

    The script is as follows: #!/bin/bash echo Enter the names of the input file and output file read input_file output_file if [ -z "$input_file" ] then echo "No input supplied" elif [ -z "$output_file" ] then $output_file=brot.axf elif [ -z "$input_file" && -z "$output_file" ] then echo "No input/output file supplied" fi

  18. How to set alias for command in bash script?

    Open the Terminal app and then type the following commands: Edit the ~/.bash_aliases or ~/.bashrc (recommended) file using a text editor: $ vi ~/.bash_aliases. … Append your bash alias. For example append: alias update='sudo yum update' Save and close the file. Activate alias by typing the following source command: How do you assign a command …

  19. Assigning one variable to another in Bash?

    Assigning one variable to another in Bash? Ask Question Asked 9 years, 2 months ago Modified 1 year, 3 months ago Viewed 61k times 16 I have a doubt. When i declare a value and assign to some variable, I don't know how to reassign the same value to another variable. See the code snippet below. #/bin/sh #declare ARG1 to a a=ARG1