Take advantage of Bash variables with our miniseries: Variables in shells.
Subscribe now
Get the highlights in your inbox every week.
In computer science (and casual computing), a variable is a location in memory that holds arbitrary information for later use. In other words, it’s a temporary storage container for you to put data into and get data out of. In the Bash shell, that data can be a word (a string, in computer lingo) or a number (an integer).
You may have never (knowingly) used a variable before on your computer, but you probably have used a variable in other areas of your life. When you say things like “give me that” or “look at this,” you’re using grammatical variables (you think of them as pronouns), because the meaning of “this” and “that” depends on whatever you’re picturing in your mind, or whatever you’re pointing to so your audience knows what you’re referring to. When you do math, you use variables to stand in for an unknown value, even though you probably don’t call it a variable.
Here’s a quick and easy demonstration of a Bash variable you may not realize you use every day. The PS1 variable holds information about how you want your terminal prompt to appear. For instance, you can set it to something very simple—like a percent sign (%)—by redefining the PS1 variable:
This article addresses variables in a Bash shell running on Linux, BSD, Mac, or Cygwin. Users of Microsoft’s open source PowerShell should refer to my article abo ut variables in PowerShell.
What are variables for?
Whether you need variables in Bash depends on what you do in a terminal. For some users, variables are an essential means of managing data, while for others they’re minor and temporary conveniences, and for still others, they may as well not exist.
Ultimately, variables are a tool. You can use them when you find a use for them, or leave them alone in the comfort of knowing they’re managed by your OS. Knowledge is power, though, and understanding how variables work in Bash can lead you to all kinds of unexpected creative problem-solving.
How to set a variable
You don’t need special permissions to create a variable. They’re free to create, free to use, and generally harmless. In a Bash shell (on Linux and Mac), you can set them by defining a variable name, and then setting its value. The following example creates a new variable called FOO and sets the value to the string /home/seth/Documents:
Success is eerily silent, so you may not feel confident that your variable got set. You can see the results for yourself with the echo command, recalling your variable by prepending it with a dollar sign ($). To ensure that the variable is read exactly as you defined it, you can also wrap it in braces and quotes. Doing this preserves any special characters that might appear in the variable; in this example, that doesn’t apply, but it’s still a good habit to form:
Setting variables can be a common thing for people who use the shell often, so the process has become somewhat informal. When a string is followed by an equal sign (=) and a value, Bash quietly assumes that you’re setting a variable, making the declare keyword unnecessary:
Variables usually are meant to convey information from one system to another. In this simple example, your variable is not very useful, but it can still communicate information. For instance, because the content of the FOO variable is a file path, you can use the variable as a shortcut to the
Variables can be any non-reserved string (along with integers and underscores). They don’t have to be capitalized, but they often are so that they’re easy to identify as variables.
How to clear a variable
You can clear a variable with the unset command:
In practice, this action is not usually necessary. Variables are relatively “cheap,” so you can create them and then forget them when you don’t need them anymore. However, there may be times you want to ensure a variable is empty to avoid conveying incorrect information to another process that might read the variable.
Create a new variable with collision protection
Sometimes, you may have reason to believe a variable was already set by you or a process. If you would rather not override it, there’s a special syntax to set a variable to its existing value unless its existing value is empty.
For this example, assume that FOO is set to /home/seth/Documents:
The colon-dash :- notation causes declare to default to an existing value. To see this process work the other way, clear the variable, and try again:
Pass variables to a child process
When you create a variable, you are creating what is called a local variable. This means that the variable is known to your current shell and only your current shell.
This setup is an intentional limitation of a variable’s scope. Variables, by design, tend to default to being locally available only, in an attempt to keep information sharing on a need-to-know basis. If you foolishly create a variable containing an important password in clear text, for example, it’s nice to know that your system won’t allow a remote shell or rogue daemon (or anything else outside the one session that created the variable) access that password.
Use the example from the beginning of this article to change your prompt, but then launch a new shell within your current one:
When you launch a new shell, the new value of PS1 is the default prompt instead of your new prompt: A child process does not inherit variables set in its parent. If you kill the child process, you return to the parent shell, and you see your custom PS1 prompt again:
If you want to pass a variable to a child process, you can prepend a command with variable definitions, or you can export the variable to the child process.
Prepending variables
You can prepend any number of variables before running a command. Whether the variables are used by the child process is up to the process, but you can pass the variables to it no matter what:
Prepending can be a useful trick when you’re running an application requiring a special location for certain libraries (using the LD_LIBRARY_PATH variable), or when you’re compiling software with a non-standard compiler (using the CC variable), and so on.
Exporting variables
Another way to make variables available to a child process is the export keyword, a command built into Bash. The export command broadens the scope of whatever variable or variables you specify:
In both cases, it’s not just a child shell that has access to a local variable that’s been passed to it or exported, it’s any child process of that shell. You can launch an application from the same shell, and that variable is available as an environment variable from within the application.
Variables exported for everything on your system to use are called environment variables, which is a topic for a future article. In the meantime, try using some variables for everyday tasks to see what they bring to your workflow.
Introduction to Bash Script Variables
For people who have been into programming, variables are a concept that is widely used irrespective of the type of programming type or language. But in case this is your firsthand on understanding variables, we would try to give an analogous circumstance to get a feeling of variable and then get into the technical aspect of variable. In a big retail store, we have a temporary store where things might be stored for a temporary purpose, and when the items in the front end are over, the ones from a temporary store are loaded into front end. Similar to that, a variable is also a temporary store for storing a piece of information. These variables are pretty handy when it comes to managing and control actions in a programming scenario. In bash script itself, these variables go a long way in allowing developers to manage and control the flow or the outcome of an algorithm in the coding world! Not only this since they are so easily adaptable to circumstances, one can land up into grave trouble if the understanding is not proper in terms of working of variables. Hence, in this article, we will make sure that there is a proper understanding of even the minute things to help you get the best in just one article!
How do Bash Script Variables work?
Now let us answer the very basic question first, how do a variable work? To answer this, we would need to first understand the 2 actions that can be performed on a variable and they are:
Web development, programming languages, Software testing & others
- Variable value setting.
- Variable value reading.
We would slowly see the following actions in place below, but for now let us come back to understand how the variable work. With the 2 actions mentioned above, a variable itself can be set and assigned a value, which essentially means that the variable is now containing a value. Now this variable will be more useful when the value assigned to the variable can be used in any operation. This is where variable value reading comes to play!
Feature
Now let us look at some feature sets which is brought to the table by variables.
- Command-line arguments: As the name suggests, these are the arguments sent through the command line. Now the bash will try to interpret the arguments sent and assign each of them to a variable. They are referenced in a special way, i.e. using $ for example, $1 for the first argument, $9 for the 9 th argument, and so on!
- $USER: This is again a reserved variable, which is assigned with a value of username of the user to run the script.
- $RANDOM: This is another reserved variable, which returns a new random variable every time it is referenced to.
- Usage of Quotes: In case a developer wants to assign a value, and this value has spaces in it, we would use quotes at the start and end of the variable to make it as a single value for assigning. The quotes can be single or double!
- Command Substitution: In some special cases we would like to execute a command on the fly and assign the result of the command to a variable. It is done easily in bash by just preceding the command with $ sign and putting the entire command within brackets!
Few pointers to be remembered while dealing with variables:
- When we read a variable for its value, we would use $ sign to reference that the name given is a variable whose value we are trying to access.
- While value is set for a variable, we don’t use the $
- As a standardized coding practice, camel-casing is the most preferred naming convention for variable names.
- There is no clear restriction on the placement of a variable.
Examples to Implement Bash Script Variables
From the above theoretical concepts we discovered some features which can be utilized effectively as a bash script argument and now in this section we will discuss an example where we would showcase the above features’ actual working right in front of your eyes giving you enough confidence to try them in real-life problem-solving.
Code:
#!/bin/bash
echo “**We would look at the arguments sent by command line:**”
echo “Argument number 1: $1”
echo “Argument number 2: $2”
echo ” ”
echo “The name of the user running the shell is: $USER”
echo “The first random number generated is: $RANDOM”
echo “The second random number generated is: $RANDOM”
var1=”World of EduCBA”
echo ” ”
echo “The varriable: $var1 has spaces but still considered as single variable: No Error”
echo “Similar to the * command @ command also prints all the values passed in the script as: [email protected]”
echo ” ”
echo “Understanding how command is substituted for a variable”
var2=$( ls | wc -l )
echo “We have $var2 entries in the current working directory!”
Output:
Conclusion
So now we can confidently say that we have in-depth covered the workings of bash script variables and this working architecture of variables is the single most important tool for bash script to help these scripts enjoy the flavor of success they currently enjoy! Some other topics are there as well like exporting of variables, but these are not widely used in the industry and hence have kept them for some other placeholder to talk about!.
Recommended Articles
This is a guide to Bash Script Variables. Here we discuss an introduction to Bash Script Variables, how does it work with programming examples. You can also go through our other related articles to learn more –
Declaring Boolean variables in bash
The syntax is as follows to define something as follows
We can now check it as follows when $failed is number such as 0 or 1:
How to declare and use Boolean variables such as “true” and “false” in a shell script
Of course, we can define them as a string and make our code more readable:
Alternate syntax is as follows to define boolean variables under bash:
Bash Boolean variable in a shell script example
Here is a sample script:
Bash Boolean testing
First, define a log file:
Let us run the rsnapshot command:
Next search for ERROR in our $log file:
If $status is not zero (failed command) or $alogs is NOT empty (errors reported by $HOME/bin/error-scanner.pl ) then alert sysadmin or developers via email/text message:
Finally, remove the $log file:
Conclusion
We explained how to declare and use Boolean variables in a shell script/bash on Linux or Unix-like systems using various methods. See the following man pages using the man command (or read it online):
$ man bash
$ help test
$ help if
- Linux / UNIX: Getting help with man pages and how to…
- Bash Pass Shell Variables To Awk Script
- Linux / Unix: Bash Shell See All Exported Variables…
- Bash Shell: Trim Leading White Space From Input Variables
- There are unfinished transactions remaining. You…
- How To: Temporarily Clear Bash Environment Variables…
- Explain: #!/bin/bash – or #!/bin/bash –…
| Category | List of Unix and Linux commands |
|---|---|
| File Management | cat |
| Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
| Network Utilities | dig • host • ip • nmap |
| OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
| Package Manager | apk • apt |
| Processes Management | bg • chroot • cron • disown • fg • jobs • killall • kill • pidof • pstree • pwdx • time |
| Searching | grep • whereis • which |
| User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
| WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Much too complicated, ”
true” and “false” are standard commands therefore the following will work and be more readable
Ah, yes. Thank you for taking the time to post an uncomplicated version.
@highbury, I reckon you know your syntax is illegal, but other than that you do’ve a point.
Introduction to Bash Export Variable
The following article provides an outline for Bash Export Variable. To start off, in case you are dabbed with other programming language, variables is something which will be quite familiar in your dictionary. For other who are not comfortable with other programming languages, a variable is a temporary placeholder to contain a number, a character or a string of characters. In bash specifically, one need not declare a variable, all we need to do is initialize or assign a value to the variable and in doing this, the variable will be created. Although these concepts are very easy to understand and use, a small deflection in understanding or their usage might make you land in a no mans land and coming out of that mess will be difficult. In other words, it is very easy and convincing to lead yourself into trouble if the understanding of the variables concept is no proper. Now before we see about what happens in the export command in bash, it is imperative to learn about how scripts work in bash.
One more thing to keep in mind is that it is absolutely not necessary to fully know the underlying principles of running a script in order to actually write a script and run it successfully, but it becomes absolutely necessary when one starts getting into complex scripts, where one script is dependent on calling another script withing itself and keeps the interaction that way for execution. In this, we have concepts of programs and processes. Program is nothing but a combination of data which allows you to run series of instructions for the CPU and then process the binary output to human recognizable format to be presented. On the other hand, a process is basically running an instance of the binary set of instructions, referred to as program. One program might have several processes running separately, independent of each other.
Web development, programming languages, Software testing & others
For example, 2 different terminals running the same copy command is an exact example. Now when we run a bash script by executing bash , obviously once all the required permissions are provided for it to execute, the command will internally create a process. This process is like an instance where all the variable sin the script itself will be existing. Now, if in another process, may be internally run by the same script we have run, we would like to access the variables within the parent script, it will be not possible at all due to permissions and restriction in-built for a bash for security reasons. Now, in order to use a variable which is invariably the one that may not be reproduced anywhere else, we can export the variable from the parent script to use it in any of the child scripts.
Syntax for the export of variable:
In our example we will also look at a live interpretation of how export is a one-way process. When we call an export, only the variable value gets exported to any of the other child processes that might be initiated. What doesn’t happen is that any change in the child process doesn’t affect the parent process. This concept comes in very handy incase one follows the methodical coding standards where a script might be broken down into smaller modular scripts and some variables needs to be exported in between the parent and corresponding child processes. For example, a small task in another big task is to create today’s dated file names form an existing directory.
So, in the parent script, the list of files can be exported and, in the child process the task of prepending of today’s date is performed. One more point to keep in mind is that, by default all the variables which are defined in the scripts or are running within an instance are local. The -p option in export command helps in printing out all the variables which are getting exported. Also, -n option removes the export property from subsequent NAMEs. Also, by default environmental variables of parent script is exported to child processes.
Example of Bash Export Variable
Given below is the example mentioned:
Code:
#!/bin/bash
echo “This is start of the parent process!”
var_exp=”Initial Value Exp”
var_noexp=”Initial Value Non”
echo “Variable to be exported is:: $var_exp”
echo ” ”
echo “Variable not to be exported is:: $var_noexp”
export var_exp
bash childProcess.sh
echo “Exported variable coming back after child process execution is:: $var_exp”
echo ” ”
echo “Non-Exported variable coming back after child process execution is:: $var_noexp”
#!/bin/bash
echo “This is start of the child process!”
echo “Variable exported is:: $var_exp”
echo ” ”
echo “Variable not exported is:: $var_noexp”
echo “Changing variable exported to child process to ‘Changed one Exp!’ to see its effect in the parent variable”
echo “Changing variable not exported to child process to ‘Changed one No_Exp!’ to see its effect in the parent variable”
var_exp=”Changed one Exp!”
var_noexp=”Changed one No_Exp!”
echo “Variable exported is changed to:: $var_exp in child process”
echo ” ”
echo “Variable not exported is changed to:: $var_noexp in child process”
I found some ways to pass external shell variables to an awk script, but I’m confused about ‘ and ” .
First, I tried with a shell script:
Why is the difference?
Lastly I tried this:
I’m confused about this.
var’ – Noam Manos May 7 ’20 at 9:29
7 Answers 7
may be done in several ways. Some are better than others. This should cover most of them. If you have a comment, please leave below. v1.5
Using -v (The best way, most portable)
Use the -v option: (P.S. use a space after -v or it will be less portable. E.g., awk -v var= not awk -vvar= )
This should be compatible with most awk , and the variable is available in the BEGIN block as well:
If you have multiple variables:
Warning. As Ed Morton writes, escape sequences will be interpreted so \t becomes a real tab and not \t if that is what you search for. Can be solved by using ENVIRON[] or access it via ARGV[]
PS If you like three vertical bar as separator ||| , it can’t be escaped, so use -F”[|][|][|]”
Example on getting data from a program/function inn to awk (here date is used)
Variable after code block
Here we get the variable after the awk code. This will work fine as long as you do not need the variable in the BEGIN block:
- Adding multiple variables:
- In this way we can also set different Field Separator FS for each file.
awk ‘some code’ FS=’,’ file1.txt FS=’;’ file2.ext
- Variable after the code block will not work for the BEGIN block:
echo “input data” | awk ‘BEGIN
Here-string
Variable can also be added to awk using a here-string from shells that support them (including Bash):
This is the same as:
P.S. this treats the variable as a file input.
ENVIRON input
As TrueY writes, you can use the ENVIRON to print Environment Variables. Setting a variable before running AWK, you can print it out like this:
ARGV input
As Steven Penny writes, you can use ARGV to get the data into awk:
To get the data into the code itself, not just the BEGIN:
Variable within the code: USE WITH CAUTION
You can use a variable within the awk code, but it’s messy and hard to read, and as Charles Duffy points out, this version may also be a victim of code injection. If someone adds bad stuff to the variable, it will be executed as part of the awk code.
This works by extracting the variable within the code, so it becomes a part of it.
If you want to make an awk that changes dynamically with use of variables, you can do it this way, but DO NOT use it for normal variables.
Here is an example of code injection:
You can add lots of commands to awk this way. Even make it crash with non valid commands.
Extra info:
Use of double quote
It’s always good to double quote variable “$variable”
If not, multiple lines will be added as a long single line.
Other errors you can get without double quote:
And with single quote, it does not expand the value of the variable:
Learn how to assign and use values in a script. Variables allow you to define and then recall values throughout a script, in order to save typing, reduce errors, and work with user-defined values when necessary.
- Course Overview
- Transcript
- View Offline
- Exercise Files
– [Instructor] Variables allow us to store, modify, … and use values by referring to them by name. … When writing scripts, we’ll use variables frequently. … In Bash, variables are an expression of parameter expansion, … which we saw a little bit of earlier. … In Bash, parameters, or in this case, variables, … are named with alphanumeric characters. … And we assign a value to that name … with an equal sign followed … by whatever value we want to store. … It’s important to remember that there’s no space … on either side of the equal sign. … Variable names are case sensitive. … In many cases, we’ll use lower case names … for our variables that you can use capitalized … or all caps names too. … Using lowercase variables helps us … to distinguish our variables from environment … and system variables, which are nearly always uppercase. … Let’s open up the script and start working with variables. … I’ll erase what I have here with Control + K. … Spaces are important. … If you put spaces around the equal sign, …
Bash Tutorial – Learn Bash Shell Scripting
About Bash
Bash is a Unix Shell. Using Bash commands we can write applications for Linux OS.
Bash Script
Bash Script is a file with commands that can be run from Linux Terminal.
Bash Tutorial
With the help of these Bash Shell Scripting tutorials, we shall learn bash scripting. Little understanding of the Linux file system and terminal commands would be helpful to get started with these tutorials.
Bash Scripting Basics
In these series of basic bash tutorials, we shall introduce you to some of the bash fundamentals.
- Tutorial – Bash Script Example: Explanation about the basic components of a bash script file
- Tutorial – Bash File Extension: Know about the file extension for a bash script and the syntax required to tell the Operating System that a file is bash script.
- Tutorial – Echo: Basic Bash Command to echo a string or variables to the terminal.
- Tutorial – Variables: Variables are used to store data. The tutorial describes bash variables and local bash variables with syntax, usage, and examples.
- Tutorial – Command Line Arguments: User can pass arguments while running the script file. The tutorial explains how to work with arguments.
- Tutorial – Read User Input: Taking input from the user is an important aspect for any kind of program/application. Learn to prompt the user for input
- Tutorial – Read Username and Password: Learn to read password without echoing back the actual password to a Linux terminal.
Bash Operators
- Bash Operators
- Tutorial – Bash Arithmetic Operators: Examples and Usage demonstration of arithmetic operators in bash scripting.
- Bash Relational Operators
- Bash Conditional Operators
Bash Conditional Statements
Conditional Statements help to branch out the program execution based on the value of an expression. Following are some of the bash tutorials that provide a broad understanding of conditional statements that can be used in bash scripting.
- Tutorial – Bash If Statement: Introduction to conditional statements with if statement. Contains syntax and examples.
- Tutorial – Bash If-Else Statement: Going a step deeper into two-level branching of program control.
- Tutorial – Bash Else-If Statement: Mulitple branching conditions in a single statement.
- Tutorial – Bash Case Statement: Executing a specific set of statements based on the value of a variable or an expression.
Bash Loops
- Tutorial – Bash For Loop: For Loop statement helps to execute a set of statements for each member of a data set or a derived data type variable.
- Tutorial – Bash While Loop: Repeat a set of statements based on an expression.
- Tutorial – Bash Until Loop: This is a little variation to while loop, but it is handy.
Bash Strings
- Tutorial – Bash String Manipulations: Some of the commonly used string operations with examples.
- Tutorial – Bash String Length: Find the length of a given string.
- Tutorial – Bash Strings Equal: To check if given two strings are the same in value or not.
- Tutorial – Bash Split String: Split a string into tokens based on a single character delimiter or another string as a delimiter.
- Tutorial – Bash Sub-String: Get the substring of a string when starting and ending index are given.
- Tutorial – Bash Concatenate Strings: Learn to concatenate two or more strings.
Bash Functions
Functions help to wrap a logical piece of a task as a functionality that could be called.
- Tutorial – Bash Functions: A basic introduction to functions in Bash Scripting.
- Tutorial – Bash Override Commands: This is interesting. You can override the built-in commands with your own set of statements.
Bash Arrays
Arrays are used to store multiple elements in a single container. Elements can be accessed using the index.
- Tutorial – Bash Array: A decent introduction to initialize an array and access elements of it in bash scripting.
Variables often look like $var, but they also look like $1, $*, $? and $$. Let’s take a look at what all these $ values can tell you.
A lot of important values are stored on Linux systems in what we call “variables,” but there are actually several types of variables and some interesting commands that can help you work with them. In a previous post, we looked at environment variables and where they are defined. In this post, we’re going to look at variables that are used on the command line and within scripts.
User variables
While it’s quite easy to set up a variable on the command line, there are a few interesting tricks. To set up a variable, all you need to do is something like this:
To display the values, you simply do this:
You can also work with your variables. For example, to increment a numeric variable, you could use any of these commands:
With some of these, you can add more than 1 to a variable’s value. For example:
With all these choices, you’ll probably find at least one that is easy to remember and convenient to use.
You can also unset a variable — basically undefining it.
Another interesting option is that you can set up a variable and make it read-only. In other words, once set to read-only, its value cannot be changed (at least not without some very tricky command line wizardry). That means you can’t unset it either.
You can use any of those setting and incrementing options for assigning and manipulating variables within scripts, but there are also some very useful internal variables for working within scripts. Note that you can’t reassign their values or increment them.
Internal variables
There are quite a few variables that can be used within scripts to evaluate arguments and display information about the script itself.
- $1, $2, $3 etc. represent the first, second, third, etc. arguments to the script.
- $# represents the number of arguments.
- $* represents the string of arguments.
- $0 represents the name of the script itself.
- $? represents the return code of the previously run command (0=success).
- $$ shows the process ID for the script.
- $PPID shows the process ID for your shell (the parent process for the script).
Some of these variables also work on the command line but show related information:
- $0 shows the name of the shell you’re using (e.g., -bash).
- $$ shows the process ID for your shell.
- $PPID shows the process ID for your shell’s parent process (for me, this is sshd).
If we throw all of these variables into a script just to see the results, we might do this:
When we call this script, we’ll see something like this:
If we check the process ID of the shell once the script is done running, we can see that it matches the PPID displayed within the script:
Of course, we’re more likely to use these variables in considerably more useful ways than simply displaying their values. Let’s check out some ways we might do this.
Checking to see if arguments have been provided:
Checking to see if a particular process is running:
Verifying that a file exists before trying to access it:
And in this little script, we check if the correct number of arguments have been provided, if the first argument is numeric, and if the second argument is an existing file.
Renaming variables
When writing a complicated script, it’s often useful to assign names to the script’s arguments rather than continuing to refer to them as $1, $2, and so on. By the 35th line, someone reading your script might have forgotten what $2 represents. It will be a lot easier on that person if you assign an important parameter’s value to $filename or $numlines.
Of course, this example script does nothing more than run the head command to show the top X lines in a file, but it is meant to show how internal parameters can be used within scripts to help ensure the script runs well or fails with at least some clarity.
Sandra Henry-Stocker has been administering Unix systems for more than 30 years. She describes herself as “USL” (Unix as a second language) but remembers enough English to write books and buy groceries. She lives in the mountains in Virginia where, when not working with or writing about Unix, she’s chasing the bears away from her bird feeders.
In every programming language variables plays an important role , in Linux shell scripting we are using two types of variables : System Defined Variables & User Defined Variables.
A variable in a shell script is a means of referencing a numeric or character value. And unlike formal programming languages, a shell script doesn’t require you to declare a type for your variables
In this article we will discuss variables, its types and how to set & use variables in shell scripting.
System Defined Variables :
These are the variables which are created and maintained by Operating System(Linux) itself. Generally these variables are defined in CAPITAL LETTERS. We can see these variables by using the command “$ set“. Some of the system defined variables are given below :
To Print the value of above variables, use echo command as shown below :
# echo $HOME
# echo $USERNAME
We can tap into these environment variables from within your scripts by using the environment variable’s name preceded by a dollar sign. This is demonstrated in the following script:
#!/bin/bash
# display user information from the system.
echo “User info for userid: $USER”
echo UID: $UID
echo HOME: $HOME
Notice that the environment variables in the echo commands are replaced by their current values when the script is run. Also notice that we were able to place the $USER system variable within the double quotation marks in the first string, and the shell script was still able to figure out what we meant. There is a drawback to using this method, however. Look at what happens in this example:
$ echo “The cost of the item is $15”
The cost of the item is 5
That is obviously not what was intended. Whenever the script sees a dollar sign within quotes, it assumes you’re referencing a variable. In this example the script attempted to display the variable $1 (which was not defined), and then the number 5. To display an actual dollar sign, you must precede it with a backslash character:
$ echo “The cost of the item is \$15”
The cost of the item is $15
That’s better. The backslash allowed the shell script to interpret the dollar sign as an actual dollar sign, and not a variable.
User Defined Variables:
These variables are defined by users. A shell script allows us to set and use our own variables within the script. Setting variables allows you to temporarily store data and use it throughout the script, making the shell script more like a real computer program.
User variables can be any text string of up to 20 letters, digits, or an underscore character. User variables are case sensitive, so the variable Var1 is different from the variable var1. This little rule often gets novice script programmers in trouble.
Values are assigned to user variables using an equal sign. No spaces can appear between the variable, the equal sign, and the value (another trouble spot for novices). Here are a few examples of assigning values to user variables:
var1=10
var2=-57
var3=testing
var4=“still more testing”
The shell script automatically determines the data type used for the variable value. Variables defined within the shell script maintain their values throughout the life of the shell script but are deleted when the shell script completes.
Just like system variables, user variables can be referenced using the dollar sign:
$ cat test3
#!/bin/bash
# testing variables
days=10
guest=”Katie”
echo “$guest checked in $days days ago”
days=5
guest=”Jessica”
echo “$guest checked in $days days ago”
$
Running the script produces the following output:
$ chmod u+x test3
$ ./test3
Katie checked in 10 days ago
Jessica checked in 5 days ago
$
Each time the variable is referenced, it produces the value currently assigned to it. It’s important to remember that when referencing a variable value you use the dollar sign, but when referencing the variable to assign a value to it, you do not use the dollar sign. Here’s an example of what I mean:
$ cat test4
#!/bin/bash
# assigning a variable value to another variable
value1=10
value2=$value1
echo The resulting value is $value2
$
When you use the value of the value1 variable in the assignment statement, you must still use the dollar sign. This code produces the following output:
$ chmod u+x test4
$ ./test4
The resulting value is 10
$
If you forget the dollar sign, and make the value2 assignment line look like:
value2=value1
you get the following output:
$ ./test4
The resulting value is value1
$
Without the dollar sign the shell interprets the variable name as a normal text string, which is most likely not what you wanted.
Use of Backtick symbol (`) in shell variables :
The backtick allows you to assign the output of a shell command to a variable. While this doesn’t seem like much, it is a major building block in script programming. You must surround the entire command line command with backtick characters:
The shell runs the command within the backticks and assigns the output to the variable testing. Here’s an example of creating a variable using the output from a normal shell command:
$ cat test5
#!/bin/bash
# using the backtick character
testing=`date`
echo “The date and time are: ” $testing
$
The variable testing receives the output from the date command, and it is used in the echo statement to display it. Running the shell script produces the following output:
$ chmod u+x test5
$ ./test5
The date and time are: Mon Jan 31 20:23:25 EDT 2011
Note : In bash you can also use the alternative $(…) syntax in place of backtick (`),which has the advantage of being re-entrant.
Example : $ echo ” Today’s date & time is :” $(date)
Today’s date & time is : Sun Jul 27 16:26:56 IST 2014
Read Also : 9 ‘diff’ Command Examples in Linux
Read Also : 16 Echo Command Examples in Linux