- Unix / Linux — Using Shell Variables
- Variable Names
- Defining Variables
- Accessing Values
- Read-only Variables
- Unsetting Variables
- Variable Types
- Linux Shell built-in variables every system admin should know
- 4. Variables — Part I
- Scope of Variables
- Books and eBooks
- Contact
- You can buy the content of this Shell Scripting Tutorial as a PDF!
- Linux shell variables
Unix / Linux — Using Shell Variables
In this chapter, we will learn how to use Shell variables in Unix. A variable is a character string to which we assign a value. The value assigned could be a number, text, filename, device, or any other type of data.
A variable is nothing more than a pointer to the actual data. The shell enables you to create, assign, and delete variables.
Variable Names
The name of a variable can contain only letters (a to z or A to Z), numbers ( 0 to 9) or the underscore character ( _).
By convention, Unix shell variables will have their names in UPPERCASE.
The following examples are valid variable names −
Following are the examples of invalid variable names −
The reason you cannot use other characters such as !, *, or — is that these characters have a special meaning for the shell.
Defining Variables
Variables are defined as follows −
The above example defines the variable NAME and assigns the value «Zara Ali» to it. Variables of this type are called scalar variables. A scalar variable can hold only one value at a time.
Shell enables you to store any value you want in a variable. For example −
Accessing Values
To access the value stored in a variable, prefix its name with the dollar sign ($) −
For example, the following script will access the value of defined variable NAME and print it on STDOUT −
The above script will produce the following value −
Read-only Variables
Shell provides a way to mark variables as read-only by using the read-only command. After a variable is marked read-only, its value cannot be changed.
For example, the following script generates an error while trying to change the value of NAME −
The above script will generate the following result −
Unsetting Variables
Unsetting or deleting a variable directs the shell to remove the variable from the list of variables that it tracks. Once you unset a variable, you cannot access the stored value in the variable.
Following is the syntax to unset a defined variable using the unset command −
The above command unsets the value of a defined variable. Here is a simple example that demonstrates how the command works −
The above example does not print anything. You cannot use the unset command to unset variables that are marked readonly.
Variable Types
When a shell is running, three main types of variables are present −
Local Variables − A local variable is a variable that is present within the current instance of the shell. It is not available to programs that are started by the shell. They are set at the command prompt.
Environment Variables − An environment variable is available to any child process of the shell. Some programs need environment variables in order to function correctly. Usually, a shell script defines only those environment variables that are needed by the programs that it runs.
Shell Variables − A shell variable is a special variable that is set by the shell and is required by the shell in order to function correctly. Some of these variables are environment variables whereas others are local variables.
Источник
Linux Shell built-in variables every system admin should know
Posted by Surendra Anne | Aug 15, 2011 | Bash | 0 |
There are many shell built-in variables which are used for administrating and writing shell scripts. In this post we will see important built-in variables and their importance. Please add any other built-ins which are useful for administration and for shell scripting.
Note: in order get present values of these variables use echo command to get them. For example if you want to see present shell then you can give echo $SHELL to get the value.
$SHELL –Gives present shell
$HISTSIZE –Gives the size of number of Commands that can be accommodated in History file
$HISTFILE –To get the history file location
$USER –Displays username
$EUID –Display UserID.
$GROUPS – To get GID info.
$PWD –Display’s present working Directory.
$HOSTNAME –Displays hostname.
$HOME –Give you user’s home directory.
$HOSTTYPE or $MACHTYPE – To get host architecture ie 32bit or 64 bit.
$OSTYPE –Detect OS, such as gnu Linux, sun sol etc. Useful for controlling the shell script flow.
$TERM –Gives you terminal name.
$TMOUT –Exit the shell, if no activity was there on terminal, useful for securing the server.
$PATH –Get path to all the binaries ie commands
$PIPESTATUS –To get exit status of piped output.
$BASH_VERSION –To get bash version. Useful for controlling the shell script flow.
$PPID –Get parent process ID.
$PS1, $PS2, $PS3, $PS4 –Different prompts. These are useful for menu driven scripts.
In Scripting
$RANDOM –To get a random number, very much useful for giving random passwords for new users.
$LINENO –To get what is the present line number the script is executing. Useful for debugging a shell script.
$REPLY –REPLY holds last read value.
$SECONDS –To get number of seconds the script is running.
Positional parameters: $1, $2, $3, $4, $5, $6, $7, $8, $9
$0 –Gives script name
$* –All positional parameters
$@ All positional parameters with spaces
$# –Number of Parameters
$$ –Current Process ID
$! –ID of Background job
$? –Error or exit status
$_ –Get the previous command last argument
Источник
4. Variables — Part I
Just about every programming language in existence has the concept of variables — a symbolic name for a chunk of memory to which we can assign values, read and manipulate its contents. The Bourne shell is no exception, and this section introduces that idea. This is taken further in Variables — Part II which looks into variables which are set for us by the environment.
Let’s look back at our first Hello World example. This could be done using variables (though it’s such a simple example that it doesn’t really warrant it!)
Note that there must be no spaces around the «=» sign: VAR=value works; VAR = value doesn’t work. In the first case, the shell sees the «=» symbol and treats the command as a variable assignment. In the second case, the shell assumes that VAR must be the name of a command and tries to execute it.
If you think about it, this makes sense — how else could you tell it to run the command VAR with its first argument being «=» and its second argument being «value»?
Enter the following code into var.sh:
This assigns the string «Hello World» to the variable MY_MESSAGE then echo es out the value of the variable.
Note that we need the quotes around the string Hello World. Whereas we could get away with echo Hello World because echo will take any number of parameters, a variable can only hold one value, so a string with spaces must be quoted so that the shell knows to treat it all as one. Otherwise, the shell will try to execute the command World after assigning MY_MESSAGE=Hello
The shell does not care about types of variables; they may store strings, integers, real numbers — anything you like.
People used to Perl may be quite happy with this; if you’ve grown up with C, Pascal, or worse yet Ada, this may seem quite strange.
In truth, these are all stored as strings, but routines which expect a number can treat them as such.
If you assign a string to a variable then try to add 1 to it, you will not get away with it:
This is because the external program expr only expects numbers. But there is no syntactic difference between:
Note though that special characters must be properly escaped to avoid interpretation by the shell.
This is discussed further in Chapter 6, Escape Characters.
We can interactively set variable names using the read command; the following script asks you for your name then greets you personally:
Mario Bacinsky kindly pointed out to me that I had originally missed out the double-quotes in line 3, which meant that the single-quote in the word «you’re» was unmatched, causing an error. It is this kind of thing which can drive a shell programmer crazy, so watch out for them!
This is using the shell-builtin command read which reads a line from standard input into the variable supplied.
Note that even if you give it your full name and don’t use double quotes around the echo command, it still outputs correctly. How is this done? With the MY_MESSAGE variable earlier we had to put double quotes around it to set it.
What happens, is that the read command automatically places quotes around its input, so that spaces are treated correctly. (You will need to quote the output, of course — e.g. echo «$MY_MESSAGE» ).
Scope of Variables
Variables in the Bourne shell do not have to be declared, as they do in languages like C. But if you try to read an undeclared variable, the result is the empty string. You get no warnings or errors. This can cause some subtle bugs — if you assign
MY_OBFUSCATED_VARIABLE=Hello
and then
echo $MY_OSFUCATED_VARIABLE
Then you will get nothing (as the second OBFUSCATED is mis-spelled).
There is a command called export which has a fundamental effect on the scope of variables. In order to really know what’s going on with your variables, you will need to understand something about how this is used.
Create a small shell script, myvar2.sh :
Now run the script:
MYVAR hasn’t been set to any value, so it’s blank. Then we give it a value, and it has the expected result.
Now run:
It’s still not been set! What’s going on?!
When you call myvar2.sh from your interactive shell, a new shell is spawned to run the script. This is partly because of the #!/bin/sh line at the start of the script, which we discussed earlier.
We need to export the variable for it to be inherited by another program — including a shell script. Type:
Now look at line 3 of the script: this is changing the value of MYVAR . But there is no way that this will be passed back to your interactive shell. Try reading the value of MYVAR :
Once the shell script exits, its environment is destroyed. But MYVAR keeps its value of hello within your interactive shell.
In order to receive environment changes back from the script, we must source the script — this effectively runs the script within our own interactive shell, instead of spawning another shell to run it.
We can source a script via the «.» (dot) command:
The change has now made it out into our shell again! This is how your .profile or .bash_profile file works, for example.
Note that in this case, we don’t need to export MYVAR .
Thanks to sway for pointing out that I’d originally said echo MYVAR above, not echo $MYVAR as it should be. Another example of an easy mistake to make with shell scripts. One other thing worth mentioning at this point about variables, is to consider the following shell script:
Think about what result you would expect. For example, if you enter «steve» as your USER_NAME, should the script create steve_file ?
Actually, no. This will cause an error unless there is a variable called USER_NAME_file . The shell does not know where the variable ends and the rest starts. How can we define this?
The answer is, that we enclose the variable itself in curly brackets:
The shell now knows that we are referring to the variable USER_NAME and that we want it suffixed with » _file «. This can be the downfall of many a new shell script programmer, as the source of the problem can be difficult to track down.
Also note the quotes around «$
Books and eBooks
My Shell Scripting books, available in Paperback and eBook formats.
Buy this tutorial as a PDF for only $5 $1!
Shell Scripting Tutorial is this tutorial, in 88-page Paperback and eBook formats. Convenient to read on the go, and to keep by your desk as an ever-present companion. | Shell Scripting: Expert Recipes for Linux, Bash and more is my 564-page book on Shell Scripting. The first half explains the features of the shell; the second half has real-world shell scripts, organised by topic, with detailed discussion of each script. |
Contact
You can mail me with this form. If you expect a reply, please ensure that the address you specify is valid. Don’t forget to include the simple addition question at the end of the form, to prove that you are a real person!
You can buy the content of this Shell Scripting Tutorial as a PDF!
Источник
Linux shell variables
In this session, we have covered how to manage environment variables in the shell. These variables are often needed by applications.
Creating variables
Variables can be created either at the shell or in shell-scripts. Any variable created within a shell script is lost when the script stops executing. A variable created at the prompt, however, will remain in existence until the shell in terminated. The syntax for creating a variable is :
Note : There will be no spaces on either side of the assignment operator (‘=’ ).
Following example creates the variable $MyVar and sets its value. It then uses echo (the command is used to display messages on the screen.) to verify the value.
case sensitive
This example shows that shell variables are case sensitive!
quotes
Notice that double quotes still allow the parsing of variables, whereas single quotes prevent this.
The bash shell will replace variables with their value in double quoted lines, but not in single quoted lines.
dollar sign($)
Another important character interpreted by the shell is the dollar sign $. The shell will look for an environment variable named like the string following the dollar sign and replace it with the value of the variable (or with nothing if the variable does not exist).
These are some examples using $HOSTNAME, $USER, $UID, $SHELL, and $HOME.
set
You can use the set command to display a list of environment variables. On Ubuntu and Debian systems, the set command will also list shell functions after the shell variables. Use set | more to see the variables then.
unset
Use the unset command to remove a variable from your shell environment.
$PS1
The $PS1 variable determines your shell prompt. You can use backslash escaped special characters like \u for the username or \w for the working directory. The bash manual has a complete reference.
In this example we change the value of $PS1 a couple of times.
To avoid unrecoverable mistakes, you can set normal user prompts to green and the root prompt to red. Add the following to your .bashrc for a green user prompt:
$PATH
The $PATH variable is determines where the shell is looking for commands to execute (unless the command is builtin or aliased). This variable contains a list of full path-names of the directories, separated by colons.
The shell will not look in the current directory for commands to execute! (Looking for executables in the current directory provided an easy way to hack PC-DOS computers). If you want the shell to look in the current directory, then add a . at the end of your $PATH.
Your path might be different when using su instead of su — because the latter will take on the environment of the target user. The root user typically has /sbin directories added to the $PATH variable.
env
The env command without options will display a list of exported variables. The difference with set with options is that set lists all variables, including those not exported to child shells. But env can also be used to start a clean shell (a shell without any inherited environment). The env -i command clears the environment for the subshell.
Notice in this screenshot that bash will set the $SHELL variable on startup.
You can use the env command to set the $LANG, or any other, variable for just one instance of bash with one command. The example below uses this to show the influence of the $LANG variable on file globbing (see the chapter on file globbing).
export
You can export shell variables to other shells with the export command. This will export the variable to child shells.
But it will not export to the parent shell (previous screenshot continued).
delineate variables
Until now, we have seen that bash interprets a variable starting from a dollar sign, continuing until the first occurrence of a non-alphanumeric character that is not an underscore. In some situations, this can be a problem. This issue can be resolved with curly braces like in this example.
The example below tries to display the value of the $MyVar variable, but it fails because the variable does not exist. By default the shell will display nothing when a variable is unbound (does not exist).
There is, however, the nounset shell option that you can use to generate an error when a variable does not exist.
In the bash shell set -u is identical to set -o nounset and likewise set +u is identical to set +o nounset.
shell embedding
Shells can be embedded on the command line, or in other words, the command line scan can spawn new processes containing a fork of the current shell. You can use variables to prove that new shells are created. In the screenshot below, the variable $var1 only exists in the (temporary) sub shell.
You can embed a shell in an embedded shell, this is called nested embedding of shells.
This screenshot shows an embedded shell inside an embedded shell.
backticks
Single embedding can be useful to avoid changing your current directory. The screenshot below uses backticks instead of dollar-bracket to embed.
You can only use the $() notation to nest embedded shells, backticks cannot do this.
backticks or single quotes
Placing the embedding between backticks uses one character less than the dollar and parenthesis combo. Be careful however, backticks are often confused with single quotes. The technical difference between ‘ and ` is significant!
shell options
Both set and unset are builtin shell commands. They can be used to set options of the bash shell itself. The next example will clarify this. By default, the shell will treat unset variables as a variable having no value. By setting the -u option, the shell will treat any reference to unset variables as an error. See the man page of bash for more information.
To list all the set options for your shell, use echo $-. The noclobber (or -C) option will be explained later in this tutorial (in the I/O redirection chapter).
When typing set without options, you get a list of all variables without function when the shell is on posix mode. You can set bash in posix mode typing set -o posix.
Exercise, Practice and Solution:
1. Use echo to display Hello followed by your username. (use a bash variable!)
Code:
2. Create a variable answer with a value of 82.
Code:
3. Copy the value of $LANG to $MyLANG.
Code:
4. List all current shell variables.
Code:
5. List all exported shell variables.
Code:
6. Do the env and set commands display your variable ?
Code:
7. Destroy your answer variable.
Code:
8. Create two variables, and export one of them.
Code:
9. Display the exported variable in an interactive child shell.
Code:
10. Create a variable, give it the value ‘Dumb’, create another variable with value ‘do’. Use echo and the two variables to echo Dumbledore.
Code:
11. Find the list of backslash escaped characters in the manual of bash. Add the time to your PS1 prompt.
Источник