LinuxSimply

Home > Bash Scripting Tutorial > Bash Variables > Variable Declaration and Assignment > Bash Variable Naming Conventions in Shell Script [6 Rules]

Bash Variable Naming Conventions in Shell Script [6 Rules]

Mohammad Shah Miran

When writing shell scripts in Bash , choosing appropriate names for variables is essential for code readability and maintainability . By adhering to consistent naming conventions , you can enhance the clarity and understandability of your scripts, making them easier to debug and modify . This article will state some rules for Bash Variable naming conventions in the shell script .

Key Takeaways

  • Learning of Bash Variable Naming Conventions.
  • Creating your own variable name using the provided materials.
  • An assignment to test your understanding of the Variable Naming Convention.

Free Downloads

6 different bash variable naming conventions in shell script.

To build a comprehensive and easily understandable code, naming the variables with a proper guideline is crucial. This also allows one to avoid any unexpected errors occurring during Debugging time.

While Bash doesn’t enforce any strict naming conventions, developers often follow certain conventions to enhance code clarity and consistency. Down below, I have discussed six different rules that should be followed while choosing your variable name.

Rule 01: Naming a Variable Using Alphabets and Numbers

While alphabets are commonly used in variable names, incorporating numbers can add a level of specificity and clarity to your code. However, bash script is a case-sensitive language which means you can store different data in the same variable having different case combinations.

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.
  • var_alphabet.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. Then, there are three variables var , VAR , and var123 created to store some data in it. Later, the echo command was used to print their stored value to prove that all those variables’ naming are correct and in compliance with the bash script naming convention.

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

❺ Use the following command to make the file executable:

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

❻ Run the script by the following command:

output image of Naming a Variable Using Alphabets and Numbers

Rule 02: Avoid Using Number at the Beginning of the Variable Name

When it comes to naming variables in Bash shell scripts, one important convention to follow is to avoid using a numeric digit as the first character of a variable name. Here is a sample example demonstrated below where I created several variables placing the number digit at the beginning and end of the variable name. The variable with the number digit at the beginning does not return its corresponding value in the execution time.

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

Script (var_number.sh) >

Here, #! /bin/bash : ‘ #! ’, is called shebang or hashbang . It indicates the interpreter to be used for executing the script, in this case, it’s bash . Next, a random variable 123var has been created by placing the number digit first. Another variable var123 is also named to show the correct way of naming. Later, the echo command displays the corresponding value contained in the variable.

output image of Avoid Using Number at the Beginning of the Variable Name

Rule 03: Using Underscore to Avoid Whitespace

If a variable name consists of multiple words , it is advisable to separate them using underscores (_). For instance, user_name is advisable instead of using username

Script (var_underscore.sh) >

The #!/bin/bash is called a shebang , and it specifies the interpreter (in this case, /bin/bash ) that should be used to execute the script. Next, the var_name variable is created and tried to display using the echo command . Similarly, another var_name variable is created to store a string inside it and displayed later.

output images of Using Underscore to Avoid Whitespace

Rule 04: No Whitespace on Either Side of the Assignment Operator(=)

When using this operator, it is recommended to have no whitespace (spaces or tabs) immediately before or after the operator. The interpreter takes it as a command instead of assigning value to the variable otherwise. Here is a relevant example stated below.

Script (var_whitespace.sh) >

Here, #! /bin/bash : ‘ #! ’, is called shebang or hashbang . It indicates the interpreter to be used for executing the script, in this case, it’s bash . Then a variable var1 is created and a whitespace is there followed by the var1 . In the case of the second variable, var2 , there is another whitespace followed by the equal sign . Both cases are wrong and thus will occur an error in execution time. Later another variable var3 has been created in the correct way and then displayed with the echo command .

output image without using Whitespace on Either Side of the Assignment Operator(=) | bash variable naming conventions in shell script

Rule 05: Avoiding Special Characters (Except Underscore)

In general, it is best to stick to alphanumeric characters ( letters and numbers ) and underscores when naming variables. Avoid using special characters , whitespace , or punctuation marks, as they can cause syntax errors or introduce unexpected behaviour. For instance, using any special character such as @, $, or # anywhere while declaring a variable is not legal.

Script (var_special_character.sh) >

Here, #! /bin/bash : ‘ #! ’, is called shebang or hashbang . It indicates the interpreter to be used for executing the script, in this case, it’s bash . Next, three different variables are created using special characters such as @, #, $. Next, all three variables are called using the echo command to display their individual data. Later, another variable var is also created and displayed using the echo command .

output image by Avoiding Special Characters | bash variable naming conventions in shell script

Rule 06: Avoid Reserved Keywords or Built-in Command Names as Variable Names

Bash has a set of reserved keywords that have special meanings and functionalities within the shell. Although you will get the variable data, to prevent conflicts and unexpected behaviour, it is crucial to avoid using these reserved keywords as variable names. Examples of reserved keywords include if , else , case , do , while, etc.

Script (var_Reserved_keyword.sh) >

Here, #! /bin/bash : ‘ #! ’, is called shebang or hashbang . It indicates the interpreter to be used for executing the script, in this case, it’s bash . Some reserved words such as while , if , elif , etc store data in this code. Then it displays the value using the echo command .

output image by Avoiding Reserved Keywords or Built-in Command Names as Variable Names | bash variable naming conventions in shell script

Comparison of Correct and Incorrect Variable Naming Conventions

Lastly, I draw a summary of the discussion in a table to describe the permissible and non-permissible ways to name the variable. Check this out to get the overall view.

Assignment on Bash Variable Naming Convention

Here I have also made a list of assignments to practice by yourself. Don’t forget to share your answer in the comment section.

  • Using uppercase letters in variable names is acceptable. (True/False)
  • We can use hyphens (-) in variable names in Bash . (True/False)
  • Bash is case-sensitive, so myVar and myvar are considered different variables. (True/False)
  • We can use Whitespace in variable names in Bash. (True/False)
  • Variable names can contain special characters like !, @, and # in Bash. (True/False)
  • Provide a valid variable name in Bash that includes both uppercase and lowercase letters, as well as an underscore .
  • Determine whether the following variable names are correct or not :
  • My variable

In conclusion, adhering to proper variable naming conventions is essential when working with Bash variables in shell scripts. In this article, I have tried to give you some must known rules to follow while choosing your variable name. Things are easy if you remember however if you have any query related to this article. Feel free to comment below. Thank you.

People Also Ask

Related Articles

  • How to Declare Variable in Bash Scripts? [5 Practical Cases]
  • How to Assign Variables in Bash Script? [8 Practical Cases]
  • How to Assign Float to Variable in Bash Script? [2 Methods]
  • 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.

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.

Ask Ubuntu is a question and answer site for Ubuntu users and developers. It only takes a minute to sign up.

Q&A for work

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

What's the difference between - (one hyphen) and -- (two hyphens) in a command? [duplicate]

Both seem to be flags but what is the difference?

  • command-line

AlphaOmega's user avatar

  • There are two answers with very different interpretations. The reason for this is because - and -- have two very different roles in two very different contexts. In the answer by @Rinzwind below, the context is command line argument flags, and it's really just by convention . This is a convention followed by many (but not all!) programs in Unix-like environments. The answer by @heemayl describes the roles that - and -- play in Bash syntax. Although you've accepted an answer, it would be helpful to clarify the question to know which context you mean. –  jvriesem Jun 3, 2020 at 19:56

4 Answers 4

- means to read the argument/content from STDIN (file descriptor 0)

-- means end of command options, everything follows that are arguments

Why needed:

Although cat can read content from STDIN without needing the - , many commands need that and their man pages mention that explicitly.

Now about -- , I have created a file -spam , let's cat the file:

Without -- , cat takes s , p , a , m all as it's options as they follow - , -- explicitly indicates the end of option(s), after that -spam is taken as a file name.

  • 5 Oh that is true too :D I assumed he meant the -- and - in front of options :D –  Rinzwind Aug 17, 2016 at 10:41
  • 1 you can also use cat ./-spam –  phuclv Aug 18, 2016 at 7:03
  • Apparently, these are just arguments, the behavior of which most likely depends on the command that uses them. –  megorit Apr 5 at 2:56
  • And how do parameters differ from arguments in this context ( -- )? –  megorit Apr 5 at 2:59
  • -- is the long name version
  • - is the short name version

Have a look at man ls and some of the options:

They are the same but some prefer the short, some the long versions.

And both are there for compatibility. Removing an option breaks software.

Not every command follows this this. As @ Bakuriu mentions in comment: a command like find has what you can consider "long names" with 1 hyphen.

In regards to coding there is something to note too:

  • Bash's getopts does not support long names.
  • The getopt from the GNU utils does.

Rinzwind's user avatar

  • 2 I believe you should also mention that not all programs follow this convention. For example find uses only the single hyphen version even for specifying long options, and other programs too. –  Bakuriu Aug 17, 2016 at 12:57
  • But then those commands dont use long options but short options ;-) Them options being long-text still makes them short :D –  Rinzwind Aug 17, 2016 at 14:17
  • 3 You should also note that short options can be (usually/often) merged, so "-abc" is not equal to "--abc", but often to "-a -b -c". This is not of course true for programs that use single dash multiletter options (e.g. openssl) –  Edheldil Aug 17, 2016 at 14:53

This actually depends on the program concerned. There are standards, but they aren't actually enforced anywhere: it's up to each program to implement them.

The find command, for example, takes full name parameters with single hyphens:

However, in general, double hyphens indicate a switch which is a full word, and single hyphens indicate a swich which is a single letter. And single-letter switches can be combined, which means that all of the following commands are equivalent:

A double hyphen followed by a space can also be used to indicate "this is the end of commands; everything that follows is a file name, even if it looks like a command".

And a single hyphen with no following letters can indicate "read from stdin, not from a file".

However, all of this is program-dependent . Any given program can violate any of these standards, as seen, for example, with find .

TRiG's user avatar

  • 1 The correct answer. –  Jacob Vlijm Aug 17, 2016 at 16:32
  • 1 +1. Maybe not even a standard, but more of a loosely held, preferred convention. –  user2943160 Aug 18, 2016 at 1:33
  • Parts of it really are standard. Not the --option , which is a GNUism, but the parsing of -vr as equivalent to -v -r (when -v is an option that does not accept an option-argument) is enshrined in POSIX utility syntax guidelines , and thus obligatory for compliant implementations of POSIX-specified tools. –  Charles Duffy Dec 19, 2017 at 17:11

One hyphen is the way options to a command traditionally has been given to Unix-commands. They have one hypen followed by a single letter (or sometimes number) ( -a -i -T ). Some options are followed by an argument ( -ofilename -o filename ).

Two hyphen is mostly used - and is the prefered way of giving options - for programs/commands on GNU-systems - ie. mostly on Linux-systems. They have two hypens followed by one or more words seperated by single hypens ( --version --ignore-case ). Options with arguments uses an equal-sign to seperate option and argument ( --log-file=filename )

The drawback with the old one-hypen options is that there are no standard letter to do the same thing over different commands. Yes, -v is often used for "verbose" - and -V is sometimes used for "version" - but there is no real consesnsus between commands. For example -i means "interactive" for cp , mv , ln and rm - the command will prompt before overwrite or delete. But it menans "ignore case" in grep . To make it even more difficult, the command sort uses -f - for "fold case" - in the same way, to ignore upper and lower case. To make the confusion complete, many commands - including mv and cp - uses -f for "force"... that the command must do something (like overwrite an existing file), even though it usually wouldn't.

On top of that, the commands for different Unix-systems (Solaris, *BSD, SysV, AIX, ...) may use different letters to do the same thing. For example the who command lists the users on a system. This command can optionally show which users accept messages from other users to their terminal - the option for this is -w under Linux, while Solaris uses -T .

Long options on the other hand, allows the same option to be used on all commands and they actually describe what the options does. For example --ignore-case , --interactive , --version , --force . Thus --ignore-case is used in both grep and sort .

But again, they are almost only used in commands/programs made as part of the GNU-project...

Finally a double hypen is used to tell a command that the list of options are finished, and that what follows are arguments - no matter how much they may look like options. If a filename starts with an hyphen (eg. -this_is_a_bad_filename ), commands may confuse it with an option and try to parse it - the double-hyphen prevent this. mv -vi -- -this_is_a_bad_filename this_is_a_better_filename (only command you should use if a filename starts with a hyphen... ;-)

Baard Kopperud's user avatar

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

  • The Overflow Blog
  • How to scale a business-ready AI platform with watsonx: Q&A with IBM sponsored post
  • Will developers return to hostile offices?
  • Featured on Meta
  • We're rolling back the changes to the Acceptable Use Policy (AUP)
  • Seeking feedback on tag colors update
  • Notifying users about the policy on AU concerning AI-generated content

Hot Network Questions

  • Distribute the code as closed source and the end users download GPLv3 dependencies separately
  • How can I remove smoke from a bag of holding?
  • What is the difference between QNH and QFF?
  • Can federal courts overturn state court decisions on matters of state law?
  • Why did Sulu know the crew complement of a Klingon Bird-of-Prey?
  • Chebyshev's Inequality Improvement
  • Exponential operator approximation: Suzuki-Trotter Expansion
  • Lack of mens rea defence to robbery
  • What's the circuitry inside triac driver optocouplers?
  • What is difference between using smtp vs relay transport type in postfix?
  • How do I make the rational numbers 0 and 1/2 in lean4?
  • What is the Mass obligation for Catholics when Christmas is on a Monday?
  • How to parse strace recvfrom syscall?
  • How to talk about two different counts
  • Phototransistor sensitivity
  • Why does phase get kicked back during refraction?
  • How can I alter this brownie recipe to make it chewier and more moist?
  • Questions about categorial propositions
  • Wavelength of "complementary colours"?
  • Breathing strategies writing choral music
  • How to survive a helicopter crash using alien biotechnology?
  • I got a problem, whenever I try joining two objects, it ends up combining the modifiers too, so it messes up everything, anyone has a solution?
  • Arranging 180 people on steps for photo
  • What are some toy models for the stable homotopy groups of spheres?

bash variables hyphen

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

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.

Super User is a question and answer site for computer enthusiasts and power users. It only takes a minute to sign up.

Q&A for work

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

What does the last "-" (hyphen) mean in options of `bash`?

In this tutorial we need to execute the following command:

What does the last - (hyphen) after bash mean?

I've seen a lot of commands with this, and couldn't find myself a logical explanation and neither find how to reformulate a google search for it. Is it the output of the piped command?

  • command-line

Kamil Maciorowski's user avatar

  • 5 Same question on Ask Ubuntu — with the same example! –  200_success Dec 30, 2018 at 3:47
  • 3 Downloading stuff from the network and piping it directly into sudo bash sounds really scary. Try looking for a tutorial that doesn't encourage such practices. –  hmakholm left over Monica Dec 30, 2018 at 16:43
  • Its the npm tutorial, but i do agree with you... –  Omar BISTAMI Dec 30, 2018 at 18:01
  • 1 If you need to search for things with symbols in them, try symbolhound.com . –  Joe Jan 1, 2019 at 5:04

3 Answers 3

Bash behaves in somewhat non-standard way when it comes to - .

POSIX says:

Guideline 10: The first -- argument that is not an option-argument should be accepted as a delimiter indicating the end of options. Any following arguments should be treated as operands, even if they begin with the - character. […] Guideline 13: For utilities that use operands to represent files to be opened for either reading or writing, the - operand should be used to mean only standard input (or standard output when it is clear from context that an output file is being specified) or a file named - .
Where a utility described in the Shell and Utilities volume of POSIX.1-2017 as conforming to these guidelines is required to accept, or not to accept, the operand - to mean standard input or output, this usage is explained in the OPERANDS section. Otherwise, if such a utility uses operands to represent files, it is implementation-defined whether the operand - stands for standard input (or standard output), or for a file named - .

But then man 1 bash reads:

A -- signals the end of options and disables further option processing. Any arguments after the -- are treated as filenames and arguments. An argument of - is equivalent to -- .

So for Bash - means neither standard input nor a file, hence somewhat non-standard.

Now your particular case:

curl -sL https://rpm.nodesource.com/setup_6.x | sudo -E bash -

I suspect the author of this command may not realize - is equivalent to -- in this case. I suspect the author wanted to make sure bash will read from its standard input, they expected - to work according to the guideline 13.

But even if it worked according to the guideline, - would be unnecessary here because bash detects when its standard input is a pipe and acts accordingly (unless -c is given etc.).

Yet - doesn't work according to the guideline, it works like -- . Still -- is unnecessary here because there are no arguments after it.

In my opinion the last - changes nothing. The command would work without it.

To see how -- and - can be useful in general, study the example below.

cat in my Kubuntu obeys both guidelines and I will use it to demonstrate usefulness of - and -- .

Let a file named foo exist. This will print the file:

Let a file named --help exist. This won't print the file:

But this will print the file named --help :

This will concatenate the file named --help with whatever comes from the standard input:

It seems you don't really need -- , because you can always pass ./--help which will be interpreted as a file for sure. But consider

when you don't know beforehand what the content of the variable is. You cannot just prepend ./ to it, because it may be an absolute path and ./ would break it. On the other hand it may be a file named --help (because why not?). In this case -- is very useful; this is a lot more robust command:

In man bash , at the end of the single-character options there is:-

If you have quoted the complete command, I can see no reason to use - after bash in this instance, but it does no harm.

AFH's user avatar

  • Thank you for your answer, Yes i have quoted the complete command. so anything after - or -- will not be seen as an option but as a file name or arguments, could you please give an example where it is useful ? –  Omar BISTAMI Dec 28, 2018 at 22:27
  • 1 It's really to allow for a script whose name begins - , an unlikely requirement, but - / -- makes it possible. –  AFH Dec 28, 2018 at 23:17
  • 1 @OmarBISTAMI Quoting a command will affect how the shell expands it, but won't affect any of the arguments which follow it. If you extend the quotes around legitimate arguments, then they become part of the command name which isn't what you want either. There are some commands which take file names as arguments, but don't use standard input by default. A contrived example allows you to sandwich input (from a terminal or a pipe) between two files. cat file1 - file2 > file3 . –  Joe Jan 1, 2019 at 5:31

bash - means that bash is waiting for stdin. So practically bash will execute whatever is returned by the command that is on the left of |

A similar but easier example would be:

echo hello | cat - here, cat will print 'hello'. Why? Because 'hello' is being sent to cat through | and cat is waiting for anything sent to it

Now let's break the entire command into two:

this curl command will return something that can be understood and executed by bash

then we have a pipe | which will send the output returned by curl command to to the right side of pipe i.e. sudo -E bash - . Finally in sudo -E bash - , bash is ready to execute anything that is sent to it

Haris Muzaffar's user avatar

You must log in to answer this question.

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

  • The Overflow Blog
  • How to scale a business-ready AI platform with watsonx: Q&A with IBM sponsored post
  • Will developers return to hostile offices?
  • Featured on Meta
  • We're rolling back the changes to the Acceptable Use Policy (AUP)
  • Seeking feedback on tag colors update

Hot Network Questions

  • Two ssh output as awk input
  • Abstract formulation of associativity
  • Putting parents with mental issues in nursing homes
  • "Make Our Life ..." vs "Make Our Lives ..."
  • Why do trigonometric functions give a seemingly incorrect result?
  • Why do we use hypothesis tests instead of just letting people do bayesian updates?
  • Write the date in abbreviated Latin
  • Convert MATLAB code solving 1D wave equation via FFT using ode45 into Mathematica code
  • PSE Advent Calendar 2023 (Day 3): 24 dangerous doors
  • What does "everything" mean?
  • Is it possible to record a Mac's screen while booting or during the initial set-up?
  • Get rid of extra white space inserted when using \verb with tabularx
  • How long should I stay in Ireland when granted entry without a visa and my passport stamped “Visa Warning Given”?
  • How do I mention low grades on the transcript due to genuine incompetence? (PhD Application)
  • Did Netanyahu say (apparently in 2001) "I actually stopped the Oslo Accords"?
  • What is the proper way to protect house from raised patio installation?
  • FET turn-on time in DC-DC converter
  • A conceptual proof that bounded index subgroups of a bounded torsion abelian group contain bounded index complemented subgroups
  • Is it possible to have higher compensation for lost hand luggage checked at the gate?
  • Difference between 幺 and 么
  • My visit visa was cancelled at the border - am I banned?
  • Why does phase get kicked back during refraction?
  • Can federal courts overturn state court decisions on matters of state law?
  • How do I typeset RTL language phrases inside a document with mostly LTR text?

bash variables hyphen

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

Previous: Bourne Shell Variables , Up: Shell Variables   [ Contents ][ Index ]

5.2 Bash Variables

These variables are set or used by Bash, but other shells do not normally treat them specially.

A few variables used by Bash are described in different chapters: variables for controlling the job control facilities (see Job Control Variables ).

($_, an underscore.) At shell startup, set to the pathname used to invoke the shell or shell script being executed as passed in the environment or argument list. Subsequently, expands to the last argument to the previous simple command executed in the foreground, after expansion. Also set to the full pathname used to invoke each command executed and placed in the environment exported to that command. When checking mail, this parameter holds the name of the mail file.

The full pathname used to execute the current instance of Bash.

A colon-separated list of enabled shell options. Each word in the list is a valid argument for the -s option to the shopt builtin command (see The Shopt Builtin ). The options appearing in BASHOPTS are those reported as ‘ on ’ by ‘ shopt ’. If this variable is in the environment when Bash starts up, each shell option in the list will be enabled before reading any startup files. This variable is readonly.

Expands to the process ID of the current Bash process. This differs from $$ under certain circumstances, such as subshells that do not require Bash to be re-initialized. Assignments to BASHPID have no effect. If BASHPID is unset, it loses its special properties, even if it is subsequently reset.

An associative array variable whose members correspond to the internal list of aliases as maintained by the alias builtin. (see Bourne Shell Builtins ). Elements added to this array appear in the alias list; however, unsetting array elements currently does not cause aliases to be removed from the alias list. If BASH_ALIASES is unset, it loses its special properties, even if it is subsequently reset.

An array variable whose values are the number of parameters in each frame of the current bash execution call stack. The number of parameters to the current subroutine (shell function or script executed with . or source ) is at the top of the stack. When a subroutine is executed, the number of parameters passed is pushed onto BASH_ARGC . The shell sets BASH_ARGC only when in extended debugging mode (see The Shopt Builtin for a description of the extdebug option to the shopt builtin). Setting extdebug after the shell has started to execute a script, or referencing this variable when extdebug is not set, may result in inconsistent values.

An array variable containing all of the parameters in the current bash execution call stack. The final parameter of the last subroutine call is at the top of the stack; the first parameter of the initial call is at the bottom. When a subroutine is executed, the parameters supplied are pushed onto BASH_ARGV . The shell sets BASH_ARGV only when in extended debugging mode (see The Shopt Builtin for a description of the extdebug option to the shopt builtin). Setting extdebug after the shell has started to execute a script, or referencing this variable when extdebug is not set, may result in inconsistent values.

When referenced, this variable expands to the name of the shell or shell script (identical to $0 ; See Special Parameters , for the description of special parameter 0). Assignment to BASH_ARGV0 causes the value assigned to also be assigned to $0 . If BASH_ARGV0 is unset, it loses its special properties, even if it is subsequently reset.

An associative array variable whose members correspond to the internal hash table of commands as maintained by the hash builtin (see Bourne Shell Builtins ). Elements added to this array appear in the hash table; however, unsetting array elements currently does not cause command names to be removed from the hash table. If BASH_CMDS is unset, it loses its special properties, even if it is subsequently reset.

The command currently being executed or about to be executed, unless the shell is executing a command as the result of a trap, in which case it is the command executing at the time of the trap. If BASH_COMMAND is unset, it loses its special properties, even if it is subsequently reset.

The value is used to set the shell’s compatibility level. See Shell Compatibility Mode , for a description of the various compatibility levels and their effects. The value may be a decimal number (e.g., 4.2) or an integer (e.g., 42) corresponding to the desired compatibility level. If BASH_COMPAT is unset or set to the empty string, the compatibility level is set to the default for the current version. If BASH_COMPAT is set to a value that is not one of the valid compatibility levels, the shell prints an error message and sets the compatibility level to the default for the current version. The valid values correspond to the compatibility levels described below (see Shell Compatibility Mode ). For example, 4.2 and 42 are valid values that correspond to the compat42 shopt option and set the compatibility level to 42. The current version is also a valid value.

If this variable is set when Bash is invoked to execute a shell script, its value is expanded and used as the name of a startup file to read before executing the script. See Bash Startup Files .

The command argument to the -c invocation option.

An array variable whose members are the line numbers in source files where each corresponding member of FUNCNAME was invoked. ${BASH_LINENO[$i]} is the line number in the source file ( ${BASH_SOURCE[$i+1]} ) where ${FUNCNAME[$i]} was called (or ${BASH_LINENO[$i-1]} if referenced within another shell function). Use LINENO to obtain the current line number.

A colon-separated list of directories in which the shell looks for dynamically loadable builtins specified by the enable command.

An array variable whose members are assigned by the ‘ =~ ’ binary operator to the [[ conditional command (see Conditional Constructs ). The element with index 0 is the portion of the string matching the entire regular expression. The element with index n is the portion of the string matching the n th parenthesized subexpression.

An array variable whose members are the source filenames where the corresponding shell function names in the FUNCNAME array variable are defined. The shell function ${FUNCNAME[$i]} is defined in the file ${BASH_SOURCE[$i]} and called from ${BASH_SOURCE[$i+1]}

Incremented by one within each subshell or subshell environment when the shell begins executing in that environment. The initial value is 0. If BASH_SUBSHELL is unset, it loses its special properties, even if it is subsequently reset.

A readonly array variable (see Arrays ) whose members hold version information for this instance of Bash. The values assigned to the array members are as follows:

The major version number (the release ).

The minor version number (the version ).

The patch level.

The build version.

The release status (e.g., beta1 ).

The value of MACHTYPE .

The version number of the current instance of Bash.

If set to an integer corresponding to a valid file descriptor, Bash will write the trace output generated when ‘ set -x ’ is enabled to that file descriptor. This allows tracing output to be separated from diagnostic and error messages. The file descriptor is closed when BASH_XTRACEFD is unset or assigned a new value. Unsetting BASH_XTRACEFD or assigning it the empty string causes the trace output to be sent to the standard error. Note that setting BASH_XTRACEFD to 2 (the standard error file descriptor) and then unsetting it will result in the standard error being closed.

Set the number of exited child status values for the shell to remember. Bash will not allow this value to be decreased below a POSIX -mandated minimum, and there is a maximum value (currently 8192) that this may not exceed. The minimum value is system-dependent.

Used by the select command to determine the terminal width when printing selection lists. Automatically set if the checkwinsize option is enabled (see The Shopt Builtin ), or in an interactive shell upon receipt of a SIGWINCH .

An index into ${COMP_WORDS} of the word containing the current cursor position. This variable is available only in shell functions invoked by the programmable completion facilities (see Programmable Completion ).

The current command line. This variable is available only in shell functions and external commands invoked by the programmable completion facilities (see Programmable Completion ).

The index of the current cursor position relative to the beginning of the current command. If the current cursor position is at the end of the current command, the value of this variable is equal to ${#COMP_LINE} . This variable is available only in shell functions and external commands invoked by the programmable completion facilities (see Programmable Completion ).

Set to an integer value corresponding to the type of completion attempted that caused a completion function to be called: TAB , for normal completion, ‘ ? ’, for listing completions after successive tabs, ‘ ! ’, for listing alternatives on partial word completion, ‘ @ ’, to list completions if the word is not unmodified, or ‘ % ’, for menu completion. This variable is available only in shell functions and external commands invoked by the programmable completion facilities (see Programmable Completion ).

The key (or final key of a key sequence) used to invoke the current completion function.

The set of characters that the Readline library treats as word separators when performing word completion. If COMP_WORDBREAKS is unset, it loses its special properties, even if it is subsequently reset.

An array variable consisting of the individual words in the current command line. The line is split into words as Readline would split it, using COMP_WORDBREAKS as described above. This variable is available only in shell functions invoked by the programmable completion facilities (see Programmable Completion ).

An array variable from which Bash reads the possible completions generated by a shell function invoked by the programmable completion facility (see Programmable Completion ). Each array element contains one possible completion.

An array variable created to hold the file descriptors for output from and input to an unnamed coprocess (see Coprocesses ).

An array variable containing the current contents of the directory stack. Directories appear in the stack in the order they are displayed by the dirs builtin. Assigning to members of this array variable may be used to modify directories already in the stack, but the pushd and popd builtins must be used to add and remove directories. Assignment to this variable will not change the current directory. If DIRSTACK is unset, it loses its special properties, even if it is subsequently reset.

If Bash finds this variable in the environment when the shell starts with value ‘ t ’, it assumes that the shell is running in an Emacs shell buffer and disables line editing.

Expanded and executed similarly to BASH_ENV (see Bash Startup Files ) when an interactive shell is invoked in POSIX Mode (see Bash POSIX Mode ).

Each time this parameter is referenced, it expands to the number of seconds since the Unix Epoch as a floating point value with micro-second granularity (see the documentation for the C library function time for the definition of Epoch). Assignments to EPOCHREALTIME are ignored. If EPOCHREALTIME is unset, it loses its special properties, even if it is subsequently reset.

Each time this parameter is referenced, it expands to the number of seconds since the Unix Epoch (see the documentation for the C library function time for the definition of Epoch). Assignments to EPOCHSECONDS are ignored. If EPOCHSECONDS is unset, it loses its special properties, even if it is subsequently reset.

The numeric effective user id of the current user. This variable is readonly.

A colon-separated list of shell patterns (see Pattern Matching ) defining the list of filenames to be ignored by command search using PATH . Files whose full pathnames match one of these patterns are not considered executable files for the purposes of completion and command execution via PATH lookup. This does not affect the behavior of the [ , test , and [[ commands. Full pathnames in the command hash table are not subject to EXECIGNORE . Use this variable to ignore shared library files that have the executable bit set, but are not executable files. The pattern matching honors the setting of the extglob shell option.

The editor used as a default by the -e option to the fc builtin command.

A colon-separated list of suffixes to ignore when performing filename completion. A filename whose suffix matches one of the entries in FIGNORE is excluded from the list of matched filenames. A sample value is ‘ .o:~ ’

An array variable containing the names of all shell functions currently in the execution call stack. The element with index 0 is the name of any currently-executing shell function. The bottom-most element (the one with the highest index) is "main" . This variable exists only when a shell function is executing. Assignments to FUNCNAME have no effect. If FUNCNAME is unset, it loses its special properties, even if it is subsequently reset.

This variable can be used with BASH_LINENO and BASH_SOURCE . Each element of FUNCNAME has corresponding elements in BASH_LINENO and BASH_SOURCE to describe the call stack. For instance, ${FUNCNAME[$i]} was called from the file ${BASH_SOURCE[$i+1]} at line number ${BASH_LINENO[$i]} . The caller builtin displays the current call stack using this information.

If set to a numeric value greater than 0, defines a maximum function nesting level. Function invocations that exceed this nesting level will cause the current command to abort.

A colon-separated list of patterns defining the set of file names to be ignored by filename expansion. If a file name matched by a filename expansion pattern also matches one of the patterns in GLOBIGNORE , it is removed from the list of matches. The pattern matching honors the setting of the extglob shell option.

An array variable containing the list of groups of which the current user is a member. Assignments to GROUPS have no effect. If GROUPS is unset, it loses its special properties, even if it is subsequently reset.

Up to three characters which control history expansion, quick substitution, and tokenization (see History Expansion ). The first character is the history expansion character, that is, the character which signifies the start of a history expansion, normally ‘ ! ’. The second character is the character which signifies ‘quick substitution’ when seen as the first character on a line, normally ‘ ^ ’. The optional third character is the character which indicates that the remainder of the line is a comment when found as the first character of a word, usually ‘ # ’. The history comment character causes history substitution to be skipped for the remaining words on the line. It does not necessarily cause the shell parser to treat the rest of the line as a comment.

The history number, or index in the history list, of the current command. Assignments to HISTCMD are ignored. If HISTCMD is unset, it loses its special properties, even if it is subsequently reset.

A colon-separated list of values controlling how commands are saved on the history list. If the list of values includes ‘ ignorespace ’, lines which begin with a space character are not saved in the history list. A value of ‘ ignoredups ’ causes lines which match the previous history entry to not be saved. A value of ‘ ignoreboth ’ is shorthand for ‘ ignorespace ’ and ‘ ignoredups ’. A value of ‘ erasedups ’ causes all previous lines matching the current line to be removed from the history list before that line is saved. Any value not in the above list is ignored. If HISTCONTROL is unset, or does not include a valid value, all lines read by the shell parser are saved on the history list, subject to the value of HISTIGNORE . The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTCONTROL .

The name of the file to which the command history is saved. The default value is ~/.bash_history .

The maximum number of lines contained in the history file. When this variable is assigned a value, the history file is truncated, if necessary, to contain no more than that number of lines by removing the oldest entries. The history file is also truncated to this size after writing it when a shell exits. If the value is 0, the history file is truncated to zero size. Non-numeric values and numeric values less than zero inhibit truncation. The shell sets the default value to the value of HISTSIZE after reading any startup files.

A colon-separated list of patterns used to decide which command lines should be saved on the history list. Each pattern is anchored at the beginning of the line and must match the complete line (no implicit ‘ * ’ is appended). Each pattern is tested against the line after the checks specified by HISTCONTROL are applied. In addition to the normal shell pattern matching characters, ‘ & ’ matches the previous history line. ‘ & ’ may be escaped using a backslash; the backslash is removed before attempting a match. The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTIGNORE . The pattern matching honors the setting of the extglob shell option.

HISTIGNORE subsumes the function of HISTCONTROL . A pattern of ‘ & ’ is identical to ignoredups , and a pattern of ‘ [ ]* ’ is identical to ignorespace . Combining these two patterns, separating them with a colon, provides the functionality of ignoreboth .

The maximum number of commands to remember on the history list. If the value is 0, commands are not saved in the history list. Numeric values less than zero result in every command being saved on the history list (there is no limit). The shell sets the default value to 500 after reading any startup files.

If this variable is set and not null, its value is used as a format string for strftime to print the time stamp associated with each history entry displayed by the history builtin. If this variable is set, time stamps are written to the history file so they may be preserved across shell sessions. This uses the history comment character to distinguish timestamps from other history lines.

Contains the name of a file in the same format as /etc/hosts that should be read when the shell needs to complete a hostname. The list of possible hostname completions may be changed while the shell is running; the next time hostname completion is attempted after the value is changed, Bash adds the contents of the new file to the existing list. If HOSTFILE is set, but has no value, or does not name a readable file, Bash attempts to read /etc/hosts to obtain the list of possible hostname completions. When HOSTFILE is unset, the hostname list is cleared.

The name of the current host.

A string describing the machine Bash is running on.

Controls the action of the shell on receipt of an EOF character as the sole input. If set, the value denotes the number of consecutive EOF characters that can be read as the first character on an input line before the shell will exit. If the variable exists but does not have a numeric value, or has no value, then the default is 10. If the variable does not exist, then EOF signifies the end of input to the shell. This is only in effect for interactive shells.

The name of the Readline initialization file, overriding the default of ~/.inputrc .

If Bash finds this variable in the environment when the shell starts, it assumes that the shell is running in an Emacs shell buffer and may disable line editing depending on the value of TERM .

Used to determine the locale category for any category not specifically selected with a variable starting with LC_ .

This variable overrides the value of LANG and any other LC_ variable specifying a locale category.

This variable determines the collation order used when sorting the results of filename expansion, and determines the behavior of range expressions, equivalence classes, and collating sequences within filename expansion and pattern matching (see Filename Expansion ).

This variable determines the interpretation of characters and the behavior of character classes within filename expansion and pattern matching (see Filename Expansion ).

This variable determines the locale used to translate double-quoted strings preceded by a ‘ $ ’ (see Locale-Specific Translation ).

This variable determines the locale category used for number formatting.

This variable determines the locale category used for data and time formatting.

The line number in the script or shell function currently executing. If LINENO is unset, it loses its special properties, even if it is subsequently reset.

Used by the select command to determine the column length for printing selection lists. Automatically set if the checkwinsize option is enabled (see The Shopt Builtin ), or in an interactive shell upon receipt of a SIGWINCH .

A string that fully describes the system type on which Bash is executing, in the standard GNU cpu-company-system format.

How often (in seconds) that the shell should check for mail in the files specified in the MAILPATH or MAIL variables. The default is 60 seconds. When it is time to check for mail, the shell does so before displaying the primary prompt. If this variable is unset, or set to a value that is not a number greater than or equal to zero, the shell disables mail checking.

An array variable created to hold the text read by the mapfile builtin when no variable name is supplied.

The previous working directory as set by the cd builtin.

If set to the value 1, Bash displays error messages generated by the getopts builtin command.

A string describing the operating system Bash is running on.

An array variable (see Arrays ) containing a list of exit status values from the processes in the most-recently-executed foreground pipeline (which may contain only a single command).

If this variable is in the environment when Bash starts, the shell enters POSIX mode (see Bash POSIX Mode ) before reading the startup files, as if the --posix invocation option had been supplied. If it is set while the shell is running, Bash enables POSIX mode, as if the command

had been executed. When the shell enters POSIX mode, it sets this variable if it was not already set.

The process ID of the shell’s parent process. This variable is readonly.

If this variable is set, and is an array, the value of each set element is interpreted as a command to execute before printing the primary prompt ( $PS1 ). If this is set but not an array variable, its value is used as a command to execute instead.

If set to a number greater than zero, the value is used as the number of trailing directory components to retain when expanding the \w and \W prompt string escapes (see Controlling the Prompt ). Characters removed are replaced with an ellipsis.

The value of this parameter is expanded like PS1 and displayed by interactive shells after reading a command and before the command is executed.

The value of this variable is used as the prompt for the select command. If this variable is not set, the select command prompts with ‘ #? ’

The value of this parameter is expanded like PS1 and the expanded value is the prompt printed before the command line is echoed when the -x option is set (see The Set Builtin ). The first character of the expanded value is replicated multiple times, as necessary, to indicate multiple levels of indirection. The default is ‘ + ’.

The current working directory as set by the cd builtin.

Each time this parameter is referenced, it expands to a random integer between 0 and 32767. Assigning a value to this variable seeds the random number generator. If RANDOM is unset, it loses its special properties, even if it is subsequently reset.

Any numeric argument given to a Readline command that was defined using ‘ bind -x ’ (see Bash Builtin Commands when it was invoked.

The contents of the Readline line buffer, for use with ‘ bind -x ’ (see Bash Builtin Commands ).

The position of the mark (saved insertion point) in the Readline line buffer, for use with ‘ bind -x ’ (see Bash Builtin Commands ). The characters between the insertion point and the mark are often called the region .

The position of the insertion point in the Readline line buffer, for use with ‘ bind -x ’ (see Bash Builtin Commands ).

The default variable for the read builtin.

This variable expands to the number of seconds since the shell was started. Assignment to this variable resets the count to the value assigned, and the expanded value becomes the value assigned plus the number of seconds since the assignment. The number of seconds at shell invocation and the current time are always determined by querying the system clock. If SECONDS is unset, it loses its special properties, even if it is subsequently reset.

This environment variable expands to the full pathname to the shell. If it is not set when the shell starts, Bash assigns to it the full pathname of the current user’s login shell.

A colon-separated list of enabled shell options. Each word in the list is a valid argument for the -o option to the set builtin command (see The Set Builtin ). The options appearing in SHELLOPTS are those reported as ‘ on ’ by ‘ set -o ’. If this variable is in the environment when Bash starts up, each shell option in the list will be enabled before reading any startup files. This variable is readonly.

Incremented by one each time a new instance of Bash is started. This is intended to be a count of how deeply your Bash shells are nested.

This variable expands to a 32-bit pseudo-random number each time it is referenced. The random number generator is not linear on systems that support /dev/urandom or arc4random , so each returned number has no relationship to the numbers preceding it. The random number generator cannot be seeded, so assignments to this variable have no effect. If SRANDOM is unset, it loses its special properties, even if it is subsequently reset.

The value of this parameter is used as a format string specifying how the timing information for pipelines prefixed with the time reserved word should be displayed. The ‘ % ’ character introduces an escape sequence that is expanded to a time value or other information. The escape sequences and their meanings are as follows; the braces denote optional portions.

A literal ‘ % ’.

The elapsed time in seconds.

The number of CPU seconds spent in user mode.

The number of CPU seconds spent in system mode.

The CPU percentage, computed as (%U + %S) / %R.

The optional p is a digit specifying the precision, the number of fractional digits after a decimal point. A value of 0 causes no decimal point or fraction to be output. At most three places after the decimal point may be specified; values of p greater than 3 are changed to 3. If p is not specified, the value 3 is used.

The optional l specifies a longer format, including minutes, of the form MM m SS . FF s. The value of p determines whether or not the fraction is included.

If this variable is not set, Bash acts as if it had the value

If the value is null, no timing information is displayed. A trailing newline is added when the format string is displayed.

If set to a value greater than zero, TMOUT is treated as the default timeout for the read builtin (see Bash Builtin Commands ). The select command (see Conditional Constructs ) terminates if input does not arrive after TMOUT seconds when input is coming from a terminal.

In an interactive shell, the value is interpreted as the number of seconds to wait for a line of input after issuing the primary prompt. Bash terminates after waiting for that number of seconds if a complete line of input does not arrive.

If set, Bash uses its value as the name of a directory in which Bash creates temporary files for the shell’s use.

The numeric real user id of the current user. This variable is readonly.

It's FOSS

Bash Basics Series #2: Using Variables in Bash

Abhishek Prakash

In the first part of the Bash Basics Series, I briefly mentioned variables. It is time to take a detailed look at them in this chapter.

If you have ever done any kind of coding, you must be familiar with the term 'variable'.

If not, think of a variable as a box that holds up information, and this information can be changed over time.

Let's see about using them.

Using variables in Bash shell

Open a terminal and use initialize a variable with a random number 4:

So now you have a variable named var and its value is 4 . Want to verify it? Access the value of a variable by adding $ before the variable name . It's called parameter expansion.

There must NOT be a space before or after = during variable initialization.

If you want, you can change the value to something else:

Using variables in shell

In Bash shell, a variable can be a number, character, or string (of characters including spaces).

Different variable types in Bash shell

Like other things in Linux, the variable names are also case-sensitive. They can consist of letters, numbers and the underscore "_".

Using variables in Bash scripts

Did you notice that I didn't run a shell script to show the variable examples? You can do a lot of things in the shell directly. When you close the terminal, those variables you created will no longer exist.

However, your distro usually adds global variables so that they can be accessed across all of your scripts and shells.

Let's write some scripts again. You should have the script directory created earlier but this command will take care of that in either case:

Basically, it will create bash_scripts directory if it doesn't exist already and then switch to that directory.

Here. let's create a new script named knock.sh with the following text.

Change the file permission and run the script. You learned it in the previous chapter.

Here's what it produced for me:

Using global variable in Bahs script

Did you notice how it added my name to it automatically? That's the magic of the global variable $USER that contains the username.

You may also notice that I used the " sometimes with echo but not other times. That was deliberate. Quotes in bash have special meanings. They can be used to handle white spaces and other special characters. Let me show an example.

Handling spaces in variables

Let's say you have to use a variable called greetings that has the value hello and welcome .

If you try initializing the variable like this:

You'll get an error like this:

This is why you need to use either single quotes or double quotes:

And now you can use this variable as you want.

Using spaces in variable names in bash

Assign the command output to a variable

Yes! You can store the output of a command in a variable and use them in your script. It's called command substitution.

Here's an example:

Command substitution in bash

The older syntax used backticks instead of $() for the command substitution. While it may still work, you should use the new, recommended notation.

Variables change the value unless you declare a 'constant' variable like this: readonly pi=3.14 . In this case, the value of variable pi cannot be changed because it was declared readonly .

🏋️ Exercise time

Time to practice what you learned. Here are some exercise to test your learning.

Exercise 1 : Write a bash script that prints your username, present working directory, home directory and default shell in the following format.

Hint : Use global variables $USER, $PWD, $HOME and $SHELL.

Exercise 2: Write a bash script that declares a variable named price . Use it to get the output in the following format:

Where X is the initial value of the variable price and it is doubled for tomorrow's prices.

Hint : Use \ to escape the special character $.

The answers to the exercises can be discussed in this dedicated thread in the community.

bash variables hyphen

In the next chapter of the Bash Basics Series, you'll see how to make the bash scripts interactive by passing arguments and accepting user inputs.

bash variables hyphen

Enjoy learning bash.

Abhishek Prakash

Created It's FOSS 11 years ago to share my Linux adventures. Have a Master's degree in Engineering and years of IT industry experience. Huge fan of Agatha Christie detective mysteries 🕵️‍♂️

Bash Basics Series #9: Functions in Bash

Bash basics series #8: for, while and until loops, bash basics series #7: if else statement, bash basics series #6: handling string operations, bash basics series #5: using arrays in bash, become a better linux user.

With the FOSS Weekly Newsletter, you learn useful Linux tips, discover applications, explore new distros and stay updated with the latest from Linux world

It's FOSS

Great! You’ve successfully signed up.

Welcome back! You've successfully signed in.

You've successfully subscribed to It's FOSS.

Your link has expired.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.

IMAGES

  1. Bash Variables

    bash variables hyphen

  2. What Are Bash Variables and How Can You Use Them?

    bash variables hyphen

  3. Bash Variables

    bash variables hyphen

  4. Bash Set Variables

    bash variables hyphen

  5. How to Use Variables in Bash Shell Scripts

    bash variables hyphen

  6. Bash Variables

    bash variables hyphen

COMMENTS

  1. Can shell variable name include a hyphen or dash (-)?

    10 Answers Sorted by: 88 I've never met a Bourne-style shell that allowed - in a variable name. Only ASCII letters (of either case), _ and digits are supported, and the first character must not be a digit. If you have a program that requires an environment variable that doesn't match the shell restrictions, launch it with the env program.

  2. bash

    Variable names used by the utilities in the Shell and Utilities volume of IEEE Std 1003.1-2001 consist solely of upper and lowercase letters, digits, and the '_' (underscore) from the characters defined in Portable Character Set and do not begin with a digit.

  3. Hyphens in variable values (in bash)

    Hyphens in variable values (in bash) [closed] Ask Question Asked 8 years, 7 months ago Modified 8 years, 7 months ago Viewed 5k times 3 Closed. This question needs details or clarity. It is not currently accepting answers. Want to improve this question? Add details and clarify the problem by editing this post. Closed 8 years ago.

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

    EXPLANATION nano: Opens a file in the Nano text editor. var_alphabet.sh: Name of the file. Copy the script mentioned below: #!/bin/bash #Variable naming using only alphabets var=35 #Using Uppercase VAR="VAR variable Contains Upper Case Letter" #Variable naming using alphabets and numbers var123=34.4 echo $var echo $VAR echo $var123 EXPLANATION

  5. Hyphen in bash function names

    1 Answer Sorted by: 0 A common misconception about Bash is that function names must follow the same rules that variables do. The Bash manual even suggests this: A word consisting solely of letters, numbers, and underscores, and beginning with a letter or underscore. Names are used as shell variable and function names.

  6. bash

    10 You can echo $- to see the currently-enabled shell options: $ echo $- himBH Those are options you can provide with a - on shell invocation — bash -h -B — or later on using set. The flags are defined in the documentation for set. My options above are: -h Locate and remember (hash) commands as they are looked up for execution.

  7. How to Work with Variables in Bash

    Linux How to Work with Variables in Bash By Dave McKay Updated Aug 12, 2023 Want to take your Linux command-line skills to the next level? Here's everything you need to know to start working with variables. Hannah Stryker / How-To Geek Readers like you help support How-To Geek.

  8. Escaping hyphens (--) with printf in bash

    Escaping hyphens (--) with printf in bash Ask Question Asked 5 years ago Modified 5 years ago Viewed 5k times 10 I have the following line: printf "---- %.55s\n" "$1 --------------" When I run this under bash I get the following error: printf: --: invalid option printf: usage: printf [-v var] format [arguments]

  9. special characters

    The bash parameter expansion manual gives us a way to obtain a list of all variables (NOT functions) in the current environment that begin with some prefix: $ {!prefix@} I have a bunch of functions that all start with foo-, such as foo-setup, foo-run, foo-initialize, etc.

  10. bash

    One hyphen is the way options to a command traditionally has been given to Unix-commands. They have one hypen followed by a single letter (or sometimes number) ( -a-i-T ). Some options are followed by an argument ( -ofilename-o filename ). Two hyphen is mostly used - and is the prefered way of giving options - for programs/commands on GNU ...

  11. bash variable interpolation separate variables by a hyphen or

    bash variable interpolation separate variables by a hyphen or underscore Asked 9 years, 1 month ago Modified 6 years, 6 months ago Viewed 3k times 4 This is a simple script just to see if the file has been downloaded. On this script the find command always evaluated to zero - even if it didn't find anything. So I commented it out.

  12. What does the last "-" (hyphen) mean in options of `bash`?

    What does the last "-" (hyphen) mean in options of `bash`? Ask Question Asked 4 years, 10 months ago Modified 4 years, 1 month ago Viewed 7k times 29 In this tutorial we need to execute the following command: # curl -sL https://rpm.nodesource.com/setup_6.x | sudo -E bash - What does the last - (hyphen) after bash mean?

  13. Bash Variables (Bash Reference Manual)

    BASH_ARGV ¶. An array variable containing all of the parameters in the current bash execution call stack. The final parameter of the last subroutine call is at the top of the stack; the first parameter of the initial call is at the bottom. When a subroutine is executed, the parameters supplied are pushed onto BASH_ARGV .

  14. What does the colon dash ":-" mean in bash

    82 This question already has answers here : Usage of :- (colon dash) in bash (2 answers) Closed 8 years ago. The result is the one desired; after a bit of trial and error. I don't understand what the "2:-" and "3:-" do/mean. Can someone explain.

  15. Use Variables in Bash Scripts [Unusual Advanced Ways]

    Sep 23, 2021 — Hunter Wittenborn Unusual Ways to Use Variables Inside Bash Scripts You probably are aware of variables in Bash shell scripting. Like other programming and scripting languages, you use variables to store the data and then reference them later in future commands. name="Linux Handbook" echo "Hello $name!"

  16. Escaping Characters in Bash

    All of these are stored as defaults in variables P0, P1, P2, and P4. However, we can modify these variables. Furthermore, we can use terminal control characters to customize our prompt: ... Many standard Bash built-ins use the - <hyphen> argument name prefix. In addition, ...

  17. How to Use Variables in Bash Shell Scripts

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

  18. What Are Bash Variables and How to Work with Them on Linux

    A bash variable acts as temporary storage for a string or a number. Bash variables are prevalent when it comes to bash scripting. Variables also make it easy for users to write complex functions and perform various operations. Users can create variables by giving them a name and a value. A name can be anything.

  19. Bash Basics #2: Use Variables in Bash Scripts

    If you have ever done any kind of coding, you must be familiar with the term 'variable'. If not, think of a variable as a box that holds up information, and this information can be changed over time. Let's see about using them. Using variables in Bash shell. Open a terminal and use initialize a variable with a random number 4: var=4