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.

File path with space as variable in bash script

I have some path with space

I need to pass this path to docker

And it doesn't work. It says there's no path /some/path . I also tried:

They don't work either

arthur.johnson221's user avatar

2 Answers 2

It's not a problem with variable assignment, you're doing it correctly. It's how you're using it.

Will, after substitution, become this:

You need to quote the argument to the docker command during invocation:

Alternatively quote just the variable. Bash merges adjacent strings, quoted or not.

gronostaj's user avatar

  • Would using parentheses in lieu of quotes also work, or would it still be incorrect after substitution? (in scripts, I always encompass path variables in parentheses [ $(my_path) ], but didn't know if that would return the correct substitution in this case) –  JW0914 Jul 9, 2021 at 11:07
  • 1 @JW0914 That would evaluate my_path as a bash command and substitute in its result, without correct quoting. my_path is not a variable name but literal command with this syntax. The correct quoting for such substitution would be "$(my_path)" , or if you want to evaluate a variable "$("$my_path")" . –  gronostaj Jul 9, 2021 at 11:50
  • 1 @JW0914 There's also the curly braces syntax ${my_path} which also doesn't affect quoting, but explicitly marks where the variable name ends and literal string begins. It also has some extra features in bash, like specifying default values if the variable is empty. –  gronostaj Jul 9, 2021 at 11:54
  • I wonder docker itself needs some escaping (e.g. \040 ). The double quote will only make sure it is passed one parameter on the shell level. –  Tom Yan Jul 9, 2021 at 13:54

Use like this

docker run --rm --mount source="""$my_path""",target="""$some_other_path""",type=bind

Neils Karlson's user avatar

  • As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center . –  Community Bot Mar 19, 2022 at 5:27

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged linux bash ..

  • The Overflow Blog
  • Spreading the gospel of Python
  • OverflowAI and the holy grail of search
  • Featured on Meta
  • Our Partnership with OpenAI
  • What deliverables would you like to see out of a working group?

Hot Network Questions

  • How can I center a tikzpicture but still add an arrow to it?
  • dir command: force output to one filename per line, full path included, but nothing else
  • Is this a school badge?
  • How to improve code finding x+y+z+w=40 to generate numbers 1 through 40?
  • Looking for a book I read in the '70s, post-apocalypse/underground bunker
  • Is a creature spell already a permanent?
  • Delta method vs actual expectation
  • How do I randomize filenames recursively?
  • "the girl with the red dress on" — What licenses the preposition "on"? What does it function as?
  • Decode Caesar cipher based on a given text
  • Simple CSRNG design based on hash function
  • Does it matter where a prenuptial agreements is signed?
  • How should one decide the author order
  • After a spacecraft departing from the ISS has performed its deorbit burn, what is the altitude at the perigee of its elliptical orbit typically?
  • Implementing basename, stpcpy, asprintf, vasprintf, strchrnul, and strcasecmp
  • What would military spies in 17th century Europe be looking for inside a city, before a siege?
  • How does a guitar string produce sound?
  • Why the color is different in two pictures in similar conditions and setting?
  • Resistor's markings don't match readings
  • `exit` man page
  • How effective are statues and other monuments in changing people's political beliefs?
  • Teaching talks as part of the interview process for a faculty position?
  • Why are search problems assumed to have the structure of "find a path in a graph"?
  • Director forcing an all day meeting on an off day before a holiday

bash assign file path to variable

TecAdmin

How to Correctly Set the $PATH variable in Bash

Bash is an acronym of Bourne-Again Shell, which is the successor of Bourne Shell distributed with most of the Linux and GNU operating systems. It comes with multiple advanced features from the previous version.

The PATH is an environment variable that stores the directories path containing the executable files.

How to Set PATH Variable?

Whenever you need to add a new executable in the PATH variable, you can either add it to the start of another directory or at the end of other directories.

The system checks for any executable under directories set in PATH from start to end. If the required binary is found in a directory, it will ignore the rest. In case, you have added an executable at the end, the system may ignore that if an executable is found with the same name in previously configured directories.

Where to Set the PATH Variable?

There are multiple scripts available in the Linux system where you can set the PATH environment variable. These scripts are executed in predefined conditions. Like, some scripts are executed during system startup, and some of them are executed at user login or logout.

Below is the list of scripts that are executed under different conditions. You can choose one of them to set the PATH variable.

System-wide Configuration:

  • /etc/bashrc: This script is invoked at system startup. Setting the PATH environment to this file will be available for all users.
  • /etc/bash.bashrc: This script is invoked for the interactive and login shells.
  • /etc/profile: This script is invoked with login shells only.
  • /etc/profile.d/*.sh: All the script with “.sh” extension are invoked by /etc/profile script.
  • /etc/environment: This is the first file that operating system uses at login. This is specifically used for setting up environment variables. This file doesn’t require to use “ export ” keyword.

User level configuration:

  • $HOME/.bashrc: This file is invoked for non-login shell.
  • $HOME/.profile: This file is invoked for the login shell. Also, this file invokes the ~/.bashrc script.

The PATH environment variable is a necessary part of the Linux and other GNU-based operating systems. You must be careful before setting up the PATH variable.

Related Posts

Shell Scripting Challenge 002! Guess the Output?

Shell Scripting Challenge 002! Guess the Output?

Shell Scripting Challenge - Day 1

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

50 bash scripting examples (part-1).

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

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

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

Mohammad Shah Miran

Mohammad Shah Miran

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

Leave a Comment Cancel reply

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

linuxsimply white logo

Get In Touch!

card

Legal Corner

dmca

Copyright © 2024 LinuxSimply | All Rights Reserved.

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 to define a variable in .bashrc so i can use it as path

Hi ( sorry for my bad English )

I just learned how to permanently set a key for a specific value using alias:

And it works perfectly fine. but then I thought myself how fun would it be if I could store my favorite paths (like ~/Music) in .bashrc for easier use. so I did this:

but It didn't work. I also tried defining a variables like this: back='..' and it also didn't work.

I know I can do alias gowork='cd ~/Workstation' but I want to be able to use the path I stored in many different commands like this:

destroy work

and I want to be able to do things like this:

go back/Pictures

Any help would be strongly appreciated thank you guys!

  • command-line
  • customization

YoloWex's user avatar

An "alias" is an abbreviation for a shell command. Your definition alias home='~' does not work because it does not specify a valid command:

This approach, therefore, is not suited to allow you to replace a full pathname by a shorter name for it that you can use in commands.

One way is to define variables instead. There is probably no need to define shortcuts for your home directory and for the previous folders: the build-in abbreviations, ~ and .. , respectively, are as short as it can get: I advise you to just adopt these.

For other paths, you can define environmental variables, which, similar as aliasses, can be made permanent by including them in .bashrc :

which then can be used in a command as

and which will work with your other aliases, e.g.

Notes if dealing with pathnames with spaces :

• If the pathname defined in the variable contains spaces, you will need to quote the variable as in

• If you define a variable with spaces, you need to keep symbols that are expanded by bash, e.g. ~ , unquoted, as in

vanadium's user avatar

  • It seems right but it returns frnr@frnr-System-Product-Name:~$ go $work bash: cd: ~/Workstation: No such file or directory –  YoloWex Jan 2, 2022 at 12:32
  • 1 @bac0n thanks, yes, the quotes prevent "~" from being expanded while setting the variable: ~ then becomes literal part of the variable, and is not expanded when retrieving its value in a command. Corrected! –  vanadium Jan 2, 2022 at 12:42
  • dropping the quotes worked!! thanks a lot ! you guy's are life savors. @vanadium –  YoloWex Jan 2, 2022 at 12:45

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged command-line customization bashrc alias ..

  • The Overflow Blog
  • Spreading the gospel of Python
  • OverflowAI and the holy grail of search
  • Featured on Meta
  • Our Partnership with OpenAI
  • What deliverables would you like to see out of a working group?

Hot Network Questions

  • What is wrong with this method of gauging the convergence of an improper integral?
  • Little Lost Robot gamma ray?
  • Movie in which the couple figurine atop a wedding cake doubles as a voodoo doll
  • Why do some Proto-Germanic nouns end with *-az?
  • Director forcing an all day meeting on an off day before a holiday
  • What exactly is the difference between causative verbs of intransitive verbs and their transitive counterpart?
  • Construct a uInt from an array of bits
  • How to track ride data for a shared bicycle?
  • Can an amphibian grow fur?
  • Jesus doesn't accuse & releases the adulterous woman, yet Matthew 5:27-28 seems to say otherwise, regarding, "whoever looks at a woman lustfully..."
  • To understand zmv ## patterns
  • Negation of "I think therefore I am"?
  • Is this "School of the Wyrm" wizard subclass I found balanced?
  • Arguments for vs against filtering Internet Access to legal Websites on University Campus
  • How to insert a pex segment with sharkbite/ push-to-fit connectors in an existing [copper] line
  • Story about someone selling his soul to the Devil and losing...with a twist
  • How effective are statues and other monuments in changing people's political beliefs?
  • How should I connect the ground wire for my lantern?
  • Do the paradoxes of material implication in relevance logic, invalidate reductio ad absurdum?
  • How to center 1st equation and align the rest?
  • Isn't it possible to display text over a video?
  • Negative pressure projectile propellants (Alternatives to gunpowder)
  • Is there any DOS game before Quake era (1996) that makes heavy use of the FPU?
  • Changing output size from a model

bash assign file path to variable

automationanywhere-en Logo

  • Developers Forum

how can we assign string file location path to file variable

  • 8 days ago 10 May 2024

Badge

  • String Package
  • File Package

Ganesh Bhat

  • Ganesh Bhat
  • Automate the Universe SME
  • 2 days ago 15 May 2024

@raj121213  

Please use file assign as bellow

bash assign file path to variable

Please mark it as resolved if you find this answer useful.

How can we close all excel and pdf files in automation anywhere

Marc 1985

@raj121213  What about this one?  

bash assign file path to variable

  • 1 day ago 16 May 2024

how can we close all file explorer and different browsers

File explorer:

taskkill /F /IM explorer.exe & start explorer

For browsers:

Edge:  taskkill /F /IM msedge.exe

Chrome: taskkill /F /IM chrome.exe

Badge

I suggest using following rather than killing explorer. This will close all kind of windows(explorer, browser etc.) unless you explicitly specify. Note: To keep the Bot editor window open, ensure that you add it in the Add window field. For example, enter *Control Room | Automation Anywhere* in the window title to keep it open.

bash assign file path to variable

  • 1 day ago 17 May 2024

@Bot Dev  This is also a good one.

But general speaking I would handle the window or program/file close different then “Window: Close all”. Normally you should know which windows needs to be closed in your solution. I never used this taskill / Window: close all solution vor several windows/program/file to be closed.

How can we close word file

Already have an account? Login

Login to the Pathfinder Community

Enter your E-mail address. We'll send you an e-mail with instructions to reset your password.

Scanning file for viruses.

Sorry, we're still checking this file's contents to make sure it's safe to download. Please try again in a few minutes.

This file cannot be downloaded

Sorry, our virus scanner detected that this file isn't safe to download.

Change the hostname of your AL2 instance

When you launch an instance into a private VPC, Amazon EC2 assigns a guest OS hostname. The type of hostname that Amazon EC2 assigns depends on your subnet settings. For more information about EC2 hostnames, see Amazon EC2 instance hostname types in the Amazon EC2 User Guide for Linux Instances .

A typical Amazon EC2 private DNS name for an EC2 instance configured to use IP-based naming with an IPv4 address looks something like this: ip-12-34-56-78.us-west-2.compute.internal , where the name consists of the internal domain, the service (in this case, compute ), the region, and a form of the private IPv4 address. Part of this hostname is displayed at the shell prompt when you log into your instance (for example, ip-12-34-56-78 ). Each time you stop and restart your Amazon EC2 instance (unless you are using an Elastic IP address), the public IPv4 address changes, and so does your public DNS name, system hostname, and shell prompt.

This information applies to Amazon Linux. For information about other distributions, see their specific documentation.

Change the system hostname

If you have a public DNS name registered for the IP address of your instance (such as webserver.mydomain.com ), you can set the system hostname so your instance identifies itself as a part of that domain. This also changes the shell prompt so that it displays the first portion of this name instead of the hostname supplied by AWS (for example, ip-12-34-56-78 ). If you do not have a public DNS name registered, you can still change the hostname, but the process is a little different.

In order for your hostname update to persist, you must verify that the preserve_hostname cloud-init setting is set to true . You can run the following command to edit or add this setting:

If the preserve_hostname setting is not listed, add the following line of text to the end of the file:

To change the system hostname to a public DNS name

Follow this procedure if you already have a public DNS name registered.

For AL2: Use the hostnamectl command to set your hostname to reflect the fully qualified domain name (such as webserver.mydomain.com ).

For Amazon Linux AMI: On your instance, open the /etc/sysconfig/network configuration file in your favorite text editor and change the HOSTNAME entry to reflect the fully qualified domain name (such as webserver.mydomain.com ).

Reboot the instance to pick up the new hostname.

Alternatively, you can reboot using the Amazon EC2 console (on the Instances page, select the instance and choose Instance state , Reboot instance ).

Log into your instance and verify that the hostname has been updated. Your prompt should show the new hostname (up to the first ".") and the hostname command should show the fully-qualified domain name.

To change the system hostname without a public DNS name

For AL2: Use the hostnamectl command to set your hostname to reflect the desired system hostname (such as webserver ).

For Amazon Linux AMI: On your instance, open the /etc/sysconfig/network configuration file in your favorite text editor and change the HOSTNAME entry to reflect the desired system hostname (such as webserver ).

Open the /etc/hosts file in your favorite text editor and change the entry beginning with 127.0.0.1 to match the example below, substituting your own hostname.

You can also implement more programmatic solutions, such as specifying user data to configure your instance. If your instance is part of an Auto Scaling group, you can use lifecycle hooks to define user data. For more information, see Run commands on your Linux instance at launch and Lifecycle hook for instance launch in the AWS CloudFormation User Guide .

Change the shell prompt without affecting the hostname

If you do not want to modify the hostname for your instance, but you would like to have a more useful system name (such as webserver ) displayed than the private name supplied by AWS (for example, ip-12-34-56-78 ), you can edit the shell prompt configuration files to display your system nickname instead of the hostname.

To change the shell prompt to a host nickname

Create a file in /etc/profile.d that sets the environment variable called NICKNAME to the value you want in the shell prompt. For example, to set the system nickname to webserver , run the following command.

Open the /etc/bashrc (Red Hat) or /etc/bash.bashrc (Debian/Ubuntu) file in your favorite text editor (such as vim or nano ). You need to use sudo with the editor command because /etc/bashrc and /etc/bash.bashrc are owned by root .

Edit the file and change the shell prompt variable ( PS1 ) to display your nickname instead of the hostname. Find the following line that sets the shell prompt in /etc/bashrc or /etc/bash.bashrc (several surrounding lines are shown below for context; look for the line that starts with [ "$PS1" ):

Change the \h (the symbol for hostname ) in that line to the value of the NICKNAME variable.

(Optional) To set the title on shell windows to the new nickname, complete the following steps.

Create a file named /etc/sysconfig/bash-prompt-xterm .

Make the file executable using the following command.

Open the /etc/sysconfig/bash-prompt-xterm file in your favorite text editor (such as vim or nano ). You need to use sudo with the editor command because /etc/sysconfig/bash-prompt-xterm is owned by root .

Add the following line to the file.

Log out and then log back in to pick up the new nickname value.

Change the hostname on other Linux distributions

The procedures on this page are intended for use with Amazon Linux only. For more information about other Linux distributions, see their specific documentation and the following articles:

How do I assign a static hostname to a private Amazon EC2 instance running RHEL 7 or Centos 7?

Warning

To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions.

Thanks for letting us know we're doing a good job!

If you've got a moment, please tell us what we did right so we can do more of it.

Thanks for letting us know this page needs work. We're sorry we let you down.

If you've got a moment, please tell us how we can make the documentation better.

IMAGES

  1. Bash Assign Output of Shell Command To Variable

    bash assign file path to variable

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

    bash assign file path to variable

  3. How Does PATH Work in Bash

    bash assign file path to variable

  4. How to Assign Variable in Bash

    bash assign file path to variable

  5. How to Assign Variable in Bash

    bash assign file path to variable

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

    bash assign file path to variable

VIDEO

  1. Beginning Bioinformatics (Part 5b)

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

  3. How to assign an output of a command to a variable #bash

  4. 07 How to Create a Shared Folder in Active Directory in Windows Server 2019_Kurdish

  5. Modify the bash prompt to indicate that the user is logged in with SSH

  6. Bash script for Directory File Listing by Extension and Creation Time

COMMENTS

  1. bash

    My problem lies with my confusion with shell variables. To my understanding, variables allow me to store a value (String in this case) and to call it later in my code. So if I wanted to have a variable that holds the path to some set of scripts, I could ideally just store it like this:

  2. How to assign File/Folder path to a Variable in Terminal

    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.. Visit Stack Exchange

  3. Store Paths and Change Directory With a Variable in the Shell

    Next, we explain the simple case of using direct paths in regular shell variables. After that, we turn to the specifics of storing a path in an array variable. Finally, we enumerate several potentially critical pitfalls related to paths in variables. We tested the code in this tutorial on Debian 11 (Bullseye) with GNU Bash 5.1.4.

  4. How to assign file name with full path to a variable in bash script

    The OP is using a graphical file manager and is asking how to include and use the path of the selected file not the directory in bash. Your answer ( while you clearly know how to do it ) needs more expanding to specifically address the OP's issue and help solve it. Also PATH in uppercase will overwrite the existing executable path variable. So ...

  5. Adding a Path to the Linux PATH Variable

    In this quick tutorial, we'll focus on how to add a path to the Linux PATH variable in Bash and Zsh. Since the methods we use for Bash work for Zsh as well, we'll first address how to add a new path to the PATH variable in Bash. Then we'll explore some Zsh specific ways to do the job. 2. PATH Variable

  6. bash

    Tour Start here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site

  7. How to Work with Variables in Bash

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

  8. 18.04

    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.. Visit Stack Exchange

  9. File path with space as variable in bash script

    (in scripts, I always encompass path variables in parentheses [$(my_path)], but didn't know if that would return the correct substitution in this case) - JW0914. ... Load ENV file from bash script. 2. Run bash scripts without typing the file extension the right way. Hot Network Questions

  10. How to retrieve a part of a path name and assign it to a variable?

    I want to assign a part of my current working directory path name to a variable and use it in a script inside the directory itself. For eg: If my pwd is :

  11. How to Correctly Set the $PATH variable in Bash

    Bash is an acronym of Bourne-Again Shell, which is the successor of Bourne Shell distributed with most of the Linux and GNU operating systems. It comes with multiple advanced features from the previous version. The PATH is an environment variable that stores the directories path containing the executable files. How to Set PATH Variable? Whenever

  12. file path in variable from user input

    Tour Start here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site

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

  14. how to define a variable in .bashrc so i can use it as path

    Your definition alias home='~' does not work because it does not specify a valid command: ~$ ~. bash: /home/vanadium: Is a directory. This approach, therefore, is not suited to allow you to replace a full pathname by a shorter name for it that you can use in commands. One way is to define variables instead.

  15. bash

    In an effort of keeping things DRY, I am trying to assign a path to a variable that may not exist and have the following script which returns: /apps/tmp: No such file or directory #!/bin/bash $ Skip to main content. Stack Exchange Network. Stack Exchange network consists of 183 Q&A communities including Stack Overflow, the largest, ...

  16. filepath

    filepath. edited Feb 23, 2016 at 0:14. asked Feb 22, 2016 at 23:51. TheVideotapes. 393 2 3 9. Yes you can use variables in path. That isn't necessarily the issue you encountered. You may be encountering some issues such as expansion of ~. Or you may be having issue with file names and directory names containing space.

  17. how can we assign string file location path to file variable

    9 views. R. raj121213. Partner. 0 replies. how can we assign string file location path to file variable. A360. String Package. File Package.

  18. Change the hostname of your AL2 instance

    webserver.mydomain.com. To change the system hostname without a public DNS name. For AL2: Use the hostnamectl command to set your hostname to reflect the desired system hostname (such as webserver ). [ec2-user ~]$ sudo hostnamectl set-hostname webserver.localdomain.

  19. bash count files in path with wildcard and assign to a variable

    list=( "some/path to the/files"/*.txt ) count=${#list[@]} Using the list of positional parameters: set -- "some/path to the/files"/*.txt count=$# In the bash shell, you will have to set the nullglob shell option using shopt -s nullglob to correctly handle empty directories (the pattern is usually left unexpanded if it does not match anything).

  20. bash: interpret string variable as file name/path

    My bash script receives a filename (or relative path) as a string, but must then read from that file. I can only read from a filename if I declare it as a literal directly in the script (without quotes)...which is impossible for arguments since they are implicitly strings to begin with.

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