How to Assign One Variable to Another in Bash

  • Linux Howtos
  • How to Assign One Variable to Another in …

Declare a Variable in Bash

Assign one variable to another in bash.

How to Assign One Variable to Another in Bash

In Bash, a variable is created by giving its reference a value. Although the built-in declare statement in Bash is not required to declare a variable directly, it is frequently used for more advanced variable management activities.

To define a variable, all you have to do is give it a name and a value. Your variables should have descriptive names that remind you of their relevance. A variable name cannot contain spaces or begin with a number.

However, it can begin with an underscore. Apart from that, any combination of uppercase and lowercase alphanumeric characters is permitted.

To create a variable in the Bash shell, you must assign a value to that variable.

Here, varname is the name of the newly created variable, and value is the value assigned to the variable. A value can be null.

Let’s look at an example.

Using the echo command, we can see the value of a variable. Whenever you refer to the value of a variable, you must prefix it with the dollar symbol $ , as seen below.

Let’s put all of our variables to work at the same time.

We can run dest=$source to assign one variable to another. The dest denotes the destination variable, and $source denotes the source variable.

Let’s assign variable a to variable b .

Hence, we can easily assign the value of one variable to another using the syntax above.

Related Article - Bash Variable

  • How to Multiply Variables in Bash
  • How to Execute Commands in a Variable in Bash Script
  • How to Increment Variable Value by One in Shell Programming
  • Bash Variable Scope
  • How to Modify a Global Variable Within a Function in Bash
  • Variable Interpolation in Bash Script

LinuxSimply

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

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

Mohammad Shah Miran

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

Key Takeaways

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

Free Downloads

Local vs global variable assignment.

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

A. Local Variable Assignment

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

Here are some key characteristics of local variable assignment:

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

Here is an example in Bash script.

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

B. Global Variable Assignment

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

Here are some key characteristics of global variable assignment:

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

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

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

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

8 Different Cases to Assign Variables in Bash Script

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

Case 01: Single Variable Assignment

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

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

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

Steps to Follow >

❶ At first, launch an Ubuntu Terminal .

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

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

❸ Copy the script mentioned below:

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

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

❺ Use the following command to make the file executable :

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

❻ Run the script by using the following command:

Single Variable Assignment

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

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

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

Script (multi_variable.sh) >

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

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

Case 03: Assigning Variables From Command-Line Arguments

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

Script (var_as_argument.sh) >

The provided Bash script starts with the shebang ( #!/bin/bash ) to use Bash shell. The script assigns the first command-line argument to the variable name , the second argument to age , and the third argument to city . The positional parameters $1 , $2 , and $3 , which represent the values passed as command-line arguments when executing the script. Then, the script uses echo statements to display the values of the assigned variables.

Assigning Variables from Command-Line Arguments

Case 04: Assign Value From Environmental Bash Variable

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

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

Script (env_variable.sh) >

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

Assign Value from Environmental Bash Variable

Case 05: Default Value Assignment

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

Script (default_variable.sh) >

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

Default Value Assignment

Case 06: Assigning Value by Taking Input From the User

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

Script (user_variable.sh) >

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

Assigning Value by Taking Input from the User

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

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

Script (let_var_assign.sh) >

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

Using the let Command for Variable Assignment

Case 08: Assigning Shell Command Output to a Variable

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

Script (shell_command_var.sh) >

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

Assigning Shell Command Output to a Variable

Assignment on Assigning Variables in Bash Scripts

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

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

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

People Also Ask

Related Articles

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

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

icon linux

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.

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

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

echo $my_name

echo $my_boost

echo $this_year

Let's use all of our variables at once:

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

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

my_boost=Tequila

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

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

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

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

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

drink_of-the_Year="$my_boost $this_year"

echo drink_of_the-Year

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

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

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

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

chmod +x fcnt.sh

Type the following to run the script:

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

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

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

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

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

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

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

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

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

Here's how you make the script executable:

chmod +x fcnt2.sh

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

./fnct2.sh /dev

./fnct2.sh /etc

./fnct2.sh /bin

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

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

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

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

The following are the other special preset variables:

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

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

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

Type the following to make it executable:

chmod +x special.sh

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

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

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

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

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

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

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

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

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

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

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

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

chmod +x script_one.shchmod +x script_two.sh

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

./script_one.sh

This is what the output tells us:

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

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

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

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

Here's an example:

site_name=How-To Geek

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

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

site_name="How-To Geek"

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

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

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

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.

Assign variable value base on another variable that doesn't yet exist in Bash

For a BASH script, I need to assign the value of another variable that does not yet exist to a variable earlier in a script. I do not however need to call upon the earlier variable until after the later variable has been assigned a value.

Basically, I need the variable, a , in line 32 (among other instances) to take on the value assigned to another variable, t , that doesn't exist until line 132 (and whose value will change with the loop). The variable a is not called upon until after t is assigned a value. I think I could find an alternate solution with a second set of CASE statements after line 135 but if what I want to accomplish is possible, it would save me time and it would be a new technique I could add too my tool belt for future scripts.

So, is what I want to do possible and if so, how can I accomplish it. Thanks in advance.

While I would still love to know if my original question can be solved in the way I described, here is my work-around solution in case anyone who stumbles onto this question wants too see a solution - even if not in the way I sought.

  • shell-script
  • bash-scripting

Brian's user avatar

  • If $a is $t why use $a at all? Just use $t on lines 142 and 143... If you change $t , just copy it to $a right before modifying it... –  Patrick Mevzek Aug 6, 2019 at 23:37
  • If you look at all the CASE instances, a can equal the values of the variables t , x , y , or z (which each change based on their respective loops -- lines 132-135). In short, I have source files titled. "Color_A_B_C_D.tif" where A..D represent four unique variables of differing ranges. Each of these files will be copied into 24 unique subfolders than change the order of the variables A..D (e.g. B_C_D_A). The loops in lines 3-6 establish what a new subfolder will be named (as expressed by test output of line 144). Each of the original files (~600) will be copied and renamed ... –  Brian Aug 7, 2019 at 0:34
  • ...with the new file name being compromised of each of the variables A..D in the respective order of the folder (and represented by line 145). However, these new files must be copied in ascending order of each respective variables value (so they can be compared against one another in a systematic fashion). There will be a command added that prefixes the order of each file in the folder with an ascending counter (e.g. 001, 002...). This is why the order they are assembled is important. ... –  Brian Aug 7, 2019 at 0:40
  • ...So, while the second set of loops (lines 132-135 will correctly assemble the new file names, the variable a in lines 32, 58, 84, or 110 are used to extract information needed to identify what the original file name is that is being copied into the new folder. As I write this, I am not sure this explanation is helping. It would be ideal to reference values in the second set of loops (132-135) and limit my need to use CASE statements to only one instance. But, I am guessing I will need to use a second set of CASE statements in the second set of loops to accomplish my task. –  Brian Aug 7, 2019 at 0:43
  • It would be way better if you provided MCVE . I'm not completely sure if my answer helps. If it solves your problem then (as far as I'm concerned) you don't have to edit the question. But next time please put some effort in creating MCVE. –  Kamil Maciorowski Aug 7, 2019 at 6:54

From Bash Reference Manual :

The basic form of parameter expansion is ${parameter} . […] If the first character of parameter is an exclamation point ( ! ), and parameter is not a nameref, it introduces a level of indirection. Bash uses the value formed by expanding the rest of parameter as the new parameter; this is then expanded and that value is used in the rest of the expansion, rather than the expansion of the original parameter. This is known as indirect expansion. The value is subject to tilde expansion, parameter expansion, command substitution, and arithmetic expansion. […] The exclamation point must immediately follow the left brace in order to introduce indirection.

So instead of

and then retrieve the value like this:

Another example:

A variable can be assigned the nameref attribute using the -n option to the declare or local builtin commands […] to create a nameref, or a reference to another variable. This allows variables to be manipulated indirectly. Whenever the nameref variable is referenced, assigned to, unset, or has its attributes modified (other than using or changing the nameref attribute itself), the operation is actually performed on the variable specified by the nameref variable’s value.

This way you don't need ! and you can even assign values indirectly. Example:

Community's user avatar

You must log in to answer this question.

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

  • The Overflow Blog
  • How do mixture-of-experts layers affect transformer models?
  • What a year building AI has taught Stack Overflow
  • Featured on Meta
  • New Focus Styles & Updated Styling for Button Groups
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network
  • Google Cloud will be Sponsoring Super User SE

Hot Network Questions

  • GR contribution to time dilation when both clocks are falling freely
  • QGIS: Removing overlapping features in one layer
  • An algebra student wants to learn to type commutative diagrams on LaTeX?
  • Why is an LLC converter's optimal Lm Lr ratio around 10?
  • What are the limitations of combining tracing GC with manual memory management?
  • Can "sit" mean "receive no attention"?
  • Why can't the Schlumpf Mountain Drive be used along with the 14-speed Rohloff?
  • Draw a car with TikZ
  • Whats the path towards enlightenment?
  • Confused as why TurboTax asking for 2022 Tax Liability to calculate 2023 underpayment penalty
  • All my windows And UI dissapeared
  • Does the EU stamp passports when travelling to and from Andorra?
  • Is there a dimensional multiplication operation?
  • Nothingness: What philosophical concept relates to how the empty set is a subset of every set?
  • Can possessive pronouns ever come on their own after a noun?
  • Is Central Limit Theorem about multiple samples or just one?
  • Variance of Estimator in Casella and Berger
  • Noise density in 1/f region
  • How to make variants of an existing command without copy the code of the command?
  • Baseball caught: Ownership? Can one leave?
  • What can I tell a student I am mentoring who claims: "I want to do pure mathematics because it is superior to any other subject in the world"?
  • Is there a way to take away an action in D&D 5e?
  • White noise fluctuation amplitude
  • How can a moral antirealist make moral normative claims?

bash assign one variable to another

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.

Referring to an existing environment variable in another

Let's say I have an environment variable named JAVA_HOME , defined in /etc/environment file. I need to append a new value JAVA_HOME/bin in the PATH variable. Consider the following,

Now if you look at it, if I could replace /usr/apps/jdk1.8.10_1/bin , with something like below, it would be more convenient.

How could I do that? Is it %JAVA_HOME%/bin ?

  • environment-variables

sourav c.'s user avatar

  • See askubuntu.com/questions/78856/… –  stalet Sep 16, 2016 at 13:20
  • @souravc- Thank you for the corrections in encoding. (y) –  Romeo Sierra Sep 16, 2016 at 13:41

2 Answers 2

You can't do that in /etc/environment . It's not a script file, and variable expansion does not work there.

To modify PATH system wide, a file with a .sh extension in the /etc/profile.d folder is a better method. It can be named myvars.sh or just about anything, as long as it has the .sh extension. In your case it might look something like this:

That way you keep the default PATH definition in /etc/environment , and modify it in your own file.

Please see the EnvironmentVariables page for reference.

Gunnar Hjalmarsson's user avatar

  • Thank you @Gunnar Hjalmarsson.. The exact answer I was looking for. I was thinking it is possible to refer to existing variables in /etc/environment . –  Romeo Sierra Sep 16, 2016 at 13:44

Referring to a variable is done by adding a $ in bash . Check this entering:

The command interpreter replaces the $variable by its value.

Your command would be:

Don't use spaces, or your command won't work.

Note: The %symbols% around a variable name are Microsoft's style.

Jos's user avatar

  • I downvoted your answer, since the OP asked about /etc/environment , which is not a script file. Please see my answer. –  Gunnar Hjalmarsson Sep 16, 2016 at 13:09
  • 1 Thank you for the points mentioned @Jos. I find them really helpful in general.. –  Romeo Sierra Sep 16, 2016 at 13:42

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged bash environment-variables ..

  • The Overflow Blog
  • How do mixture-of-experts layers affect transformer models?
  • What a year building AI has taught Stack Overflow
  • Featured on Meta
  • New Focus Styles & Updated Styling for Button Groups
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network
  • AI-generated content is not permitted on Ask Ubuntu
  • Let's organize some chat workshops

Hot Network Questions

  • What kind of alien technology would make space colonization viable?
  • A very short story about a painting that took the life of the model
  • Why do you need to set aside 10 cards when setting up the game?
  • Why is an LLC converter's optimal Lm Lr ratio around 10?
  • Adding two numbers in Tally marks
  • Adverb position before object / before verb
  • Is it safe to eat yellow yam, which I pan-fried?
  • White noise fluctuation amplitude
  • What are examples of "Official Observations" in a passport?
  • I need a word for the atmosphere between two people
  • What can I tell a student I am mentoring who claims: "I want to do pure mathematics because it is superior to any other subject in the world"?
  • Academic view of graduates who go to US national labs?
  • Should I initialize third party libraries in a class or function?
  • Time dilation on a heavily oblong planet
  • Can every spanning tree result from a depth-first search?
  • What is this display for on the Embraer E175?
  • Fill a matrix with randomly placed elements that are a certain distance apart
  • Any practical use for the underscore variable?
  • Draw a Fibonacci Swoosh
  • Should the banker hit?
  • Masyu: Four Colours
  • Under what circumstances did Aziz Isa Elkun lose contact with his mother?
  • Does the New Testament state that Jesus Christ is the 'image' and the 'likeness' of God?
  • Can possessive pronouns ever come on their own after a noun?

bash assign one variable to another

Shell Programming and Scripting

Shell assign variable to another variable.

Member Information Avatar

10 More Discussions You Might Find Interesting

1. shell programming and scripting, how to assign awk values to shell variable, discussion started by: green_k, 2. unix for beginners questions & answers, how can i assign awk's variable to shell script's variable, discussion started by: geomarine, 3. shell programming and scripting, how to assign more than 1 variable value from 1 common shell to many other shell files, discussion started by: gl@)ator, 4. shell programming and scripting, how to assign a shell variable to a number parameter in pl/sql, discussion started by: vel4ever, 5. unix for dummies questions & answers, assign sql result in shell variable, discussion started by: matt01, 6. shell programming and scripting, assign perl output to ksh shell variable, discussion started by: swimp, 7. shell programming and scripting, how to assign record count output of isql to a shell variable , discussion started by: vikram3.r, 8. shell programming and scripting, assign awk's variable to shell script's variable, discussion started by: tiger2000, 9. shell programming and scripting, how to assign the result of a sql command to more than one variable in shell script., discussion started by: little_wonder, 10. shell programming and scripting, how to assign sql output data to shell script variable, discussion started by: kattics, member badges and information modal.

MarketSplash

How To Export A Bash Variable To Parent Shell: Steps And Techniques

Communicating between child and parent shells is a nuanced topic, especially when it comes to bash variables. This article delves into the practical approaches and methods to successfully export these variables to a parent shell.

💡 KEY INSIGHTS

  • Understanding Variable Scopes: Bash variables can be local, global, or exported, and understanding their scope is crucial for effective scripting.
  • Techniques for Exporting Variables: Creative methods like the source command and process substitution are essential to export variables to a parent shell in Bash.
  • Common Pitfalls and Solutions: Recognizing and rectifying common mistakes, such as uninitialized variables and improper permissions, enhances script reliability.
  • Child-to-Parent Shell Communication: Employing temporary files and named pipes (FIFOs) facilitates complex communication between child and parent shells.

Working with bash often requires a nuanced understanding of its environment variables. Sometimes, you might find the need to propagate a variable's value to the parent shell, which isn't a direct operation. This piece will help you grasp the right techniques to achieve that.

bash assign one variable to another

Understanding Bash Variables And Their Scope

Setting and using bash variables, child to parent shell communication, methods to export variables to parent shell, common mistakes and their fixes, frequently asked questions.

Bash variables are an essential component of shell scripting, offering a way to store and retrieve data. These variables can either be local or global, depending on their defined scope.

Local Variables

Global variables, exported variables.

Local variables are only accessible within the script or function where they were defined. Once the script or function ends, these variables are no longer accessible.

On the contrary, global variables are accessible throughout the entire script. They are the default variable type in bash unless specified otherwise.

Variables can also be exported to child processes but, by default, they cannot be propagated to parent processes.

In this example, exported_var is available in the child shell because it was exported.

Variables in Bash are utilized to hold and manage data. Properly setting and using these variables is key to creating effective and efficient scripts.

Declaring Variables

Accessing variables, variable reassignment, special variables.

In Bash, a variable is declared by simply assigning a value to a name without spaces.

To access the value stored in a variable, prefix the variable's name with a dollar sign ($) .

Variables in Bash can be reassigned with new values.

Bash provides special variables that can be utilized to get specific data, such as the number of arguments or the script's name.

For instance, if a script named myscript.sh is run with the command ./myscript.sh arg1 arg2 , $# would return 2, $0 would return myscript.sh , and $1 would return arg1 .

In the realm of Bash scripting, shells can spawn child processes. However, a typical dilemma is the communication between a child shell and its parent. Unlike conventional programming languages, where data flows both ways easily, Bash has certain constraints.

Child Shell Behavior

Communicating variables upwards, using temporary files.

A child shell is a new instance of the shell. It inherits environment variables from the parent but doesn't share its memory space.

Directly modifying parent shell variables from a child shell isn't feasible. However, a common workaround is to capture output from a child shell and assign it in the parent.

For more complex communication , temporary files can be employed.

This method involves creating a temporary file. The child shell writes data to this file, which the parent shell then reads. After usage, always remember to delete the temporary file to free up resources.

In Bash, the communication flow from child shells to parent shells is naturally restrictive. Yet, there are crafty techniques to export variables upwards . These methods are essential for scenarios where such data sharing is paramount.

Source Command

Process substitution, named pipes (fifos), aliasing commands.

The source command (or its alias . ) is a popular method. It allows executing a script in the current shell environment rather than spawning a new one.

This method employs a unique feature of Bash that allows treating the output of a command as a file .

Code Example:

With this approach, each grep command's output acts like a file input for the diff command. This allows John to see the differences in the "ERROR" lines between the two log files without creating any intermediate files.

FIFOs, another advanced feature, can facilitate bidirectional communication between shells.

Though less common, you can alias a command that exports a variable, effectively allowing its value to be set in the parent.

When working with Bash and shell scripting, certain pitfalls often ensnare even seasoned programmers. Recognizing and rectifying these common mistakes is crucial for efficient scripting.

Uninitialized Variables

Incorrect command substitution, forgetting quotations, improper permissions, using test commands incorrectly.

A frequent oversight is using an uninitialized variable, leading to unexpected behaviors.

Fix: Always initialize variables before usage or employ default values.

Misusing backticks (`) instead of the preferred $() for command substitution can introduce errors.

Fix: Always use $() for clarity and nested command substitution.

Overlooking quotations, especially with variables containing spaces, can lead to unexpected results.

Fix: Always quote variables.

Attempting to run a script without execution permissions is another common error.

Fix: Grant the necessary permissions using chmod .

When testing conditions, incorrect usage of test commands can produce unintended outcomes.

Fix: Always ensure proper spacing and comparison operators.

What does it mean to export a bash variable to the parent shell?

Exporting a variable means making it available to child processes of the current shell session. However, by default, you cannot send a variable up to a parent shell. Special techniques, like sourcing a script or using command substitution, are needed to achieve something similar.

How do I check if my variable has been successfully exported in bash?

You can use the env or printenv commands to list all environment variables. If your exported variable appears in the list, it has been successfully exported.

Why can't I see my exported variable in a new terminal window?

Each terminal window usually represents a new shell session. Exporting a variable in one session doesn't make it available in other sessions. If you want a variable to be available in all sessions, consider adding the export command to your .bashrc or .bash_profile file.

Is there a difference between setting a bash variable and exporting it?

Yes. Setting a variable makes it available only within the current shell session. Exporting it makes it an environment variable, which means it's accessible to child processes spawned by the shell.

Let’s test your knowledge!

How To Export A Bash Variable To Parent Shell

Continue learning with these bash shell guides.

  • Exiting The Bash Shell: How To Safely Close Your Terminal Session
  • Bash Shell Testing: Strategies And Best Practices
  • How To Enhance Productivity With Bash Shell Scripting
  • Comparing Strings In Bash Shell: A Beginner's Guide
  • Mastering Bash Shell Arrays

Subscribe to our newsletter

Subscribe to be notified of new content on marketsplash..

IMAGES

  1. Bash Script: define las variables Bash y sus tipos

    bash assign one variable to another

  2. How to use Variables in Bash Programming

    bash assign one variable to another

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

    bash assign one variable to another

  4. How to use Variables in Bash

    bash assign one variable to another

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

    bash assign one variable to another

  6. How to Assign Variable in Bash

    bash assign one variable to another

VIDEO

  1. Assign Multiple Materials to a Static Mesh

  2. How to recode variables in R

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

  4. Difference between local and global variable

  5. Functions In Bash

  6. P-3 Parking Game How to access a variable from another script in Unity 3d || unity

COMMENTS

  1. Assigning one variable to another in Bash?

    A=(a a a) declare -n VAR=A # "-n" stands for "name", e.g. a new name for the same variable. VAR+=(b) echo "${A[@]}" # prints "a a a b". That is, VAR becomes effectively the same as the original variable. Instead of copying, you're adding an alias. Here's an example with functions: function myFunc() {.

  2. How to Assign One Variable to Another in Bash

    Declare a Variable in Bash. To create a variable in the Bash shell, you must assign a value to that variable. Syntax: varname=value. Here, varname is the name of the newly created variable, and value is the value assigned to the variable. A value can be null. Let's look at an example. $ me=superman.

  3. bash

    I need a small correction for my below code. I am trying to assign variable value to another variable, but it's not working. please help me. Below is my script. #!/bin/sh choice=1 VAL1="test" if ...

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

    The first line #!/bin/bash specifies the interpreter to use (/bin/bash) for executing the script.Then, three variables x, y, and z are assigned values 1, 2, and 3, respectively.The echo statements are used to print the values of each variable.Following that, two variables var1 and var2 are assigned values "Hello" and "World", respectively.The semicolon (;) separates the assignment ...

  5. How to Work with Variables in Bash

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

  6. How do I set a bash variable that contains another variable?

    See also Storing output of command in shell variable, Calculate variable and output it to another variable, Bash: Assign output of pipe to a variable, setting output of a command to a variable, and more. -

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

  8. bash

    It seems a similar question was answered here.. You can of course use . or source to assign the variables if you are comfortable, but you can also use awk or grep to only run specific lines from the file that look like variable declerations.. How to handle many variables. If you want to source all the variables assigned in script1.sh, consider:. source <(grep -E '^\w+=' script1.sh)

  9. Assign values to shell variables

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

  10. Linux Bash: Multiple Variable Assignment

    Take a closer look at how to do multiple variable assignment in Bash scripts. ... we've assigned seven variables in one shot using the process substitution and IO redirection trick. ... Another way to assign multiple variables using a command's output is to assign the command output fields to an array.

  11. shell script

    Basically, I need the variable, a, in line 32 (among other instances) to take on the value assigned to another variable, t, that doesn't exist until line 132 (and whose value will change with the loop). The variable a is not called upon until after t is assigned a value. I think I could find an alternate solution with a second set of CASE ...

  12. bash

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

  13. How do I assign a variable in Bash whose name is expanded ($) from

    TL;DR: One way is local tmp="notif_$2"; printf -v "old_notif" "%d" "${!tmp}". You are trying to expand a parameter (in this case, a variable) whose name must itself be obtained by expanding another parameter (in this case, a positional parameter). Furthermore, the positional parameter must be expanded, then concatenated with the text notif_, to ...

  14. bash

    You can't do that in /etc/environment.It's not a script file, and variable expansion does not work there. To modify PATH system wide, a file with a .sh extension in the /etc/profile.d folder is a better method. It can be named myvars.sh or just about anything, as long as it has the .sh extension. In your case it might look something like this:

  15. Shell assign variable to another variable

    Hi Gurus, I have a script which assign awk output to shell variable. current it uses two awk command to assign value to two variables. I want to use one command to assign two values to two variables. I tried the code, but it does't work. kindly provide your suggestion. current code... (2 Replies)

  16. Use a variable reference "inside" another variable

    For your use case, in any shell with arrays (all ksh variants, bash ≥2.0, zsh), you can assign to an array variable and take the element you wish. Beware that ksh and bash arrays start numbering at 0, but zsh starts at 1 unless you issue setopt ksh_arrays or emulate ksh. set -A iostat -- $(iostat) echo "${iostat[5]}"

  17. PDF UNIX essentials (hands-on)

    → similarly, shell variables are generally all lower-case → set environment variables using "setenv" (as opposed to the "set" command) → without any parameters, the "setenv" command will display all variables → the "setenv" command will only set or assign one variable at a time → the format for the command to set a value is (without ...

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

    As an aside, all-caps variables are defined by POSIX for variable names with meaning to the operating system or shell itself, whereas names with at least one lowercase character are reserved for application use. Thus, consider using lowercase names for your own shell variables to avoid unintended conflicts (keeping in mind that setting a shell variable will overwrite any like-named environment ...

  19. How To Export A Bash Variable To Parent Shell: Steps And ...

    💡 KEY INSIGHTS; Understanding Variable Scopes: Bash variables can be local, global, or exported, and understanding their scope is crucial for effective scripting. Techniques for Exporting Variables: Creative methods like the source command and process substitution are essential to export variables to a parent shell in Bash. Common Pitfalls and Solutions: Recognizing and rectifying common ...

  20. bash

    The difference is that I source the variables.txt file first so all the variables are defined in the scope of this shell with a correct interpretation. Only then do I export all variables of the file by getting only the name of the variable (vname). On a side note, you should protect your variables with ${}.

  21. Copy values between variables in bash script

    How can I copy the numeric value in a variable to another variable in bash script. If this were C, I would do. int a=0; int b; a=b; I am trying to do this: ... Assigning one variable to another in Bash? Related. 3. Copy a variable in shell script (Linux) 0.

  22. Linux Bash: Variable to another variable

    Linux Bash: Variable to another variable [duplicate] Ask Question Asked 4 years, 9 months ago. ... While removing one trailing newline is usually helpful, removing the other ones is almost always unwanted. ... Bash - assign array into variable as string. 1.