- Unix / Linux — Using Shell Variables
- Variable Names
- Defining Variables
- Accessing Values
- Read-only Variables
- Unsetting Variables
- Variable Types
- Bash Beginner Series #2: Understanding Variables in Bash Shell Scripting
- Using variables in bash shell scripts
- Step by step explanation of the above shell script
- Integers, strings or characters? How to create different variable data types in bash shell?
- Constant variables in bash shell
- Command substitutions
- Before you go, try turning Hello World script to a smart HelloWorld script
- 4. Variables — Part I
- Scope of Variables
- Books and eBooks
- Contact
- You can buy the content of this Shell Scripting Tutorial as a PDF!
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.
Источник
Bash Beginner Series #2: Understanding Variables in Bash Shell Scripting
Time changes, and so do variables!
You must have played with variables quite a bit if you did any sort of programming.
If you never worked with variables before, you can think of them as a container that stores a piece of information that can vary over time.
Variables always come in handy while writing a bash script and in this tutorial, you will learn how to use variables in your bash scripts.
Using variables in bash shell scripts
In the last tutorial in this series, you learned to write a hello world program in bash.
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. Edit your hello.sh script and use read command to get input from the user:
Now if you run your hello.sh script; it will prompt you for your name and then it will greet you with whatever name you provide to it:
In the above example, I entered Elliot as my name and then the script greeted me with “Hello, Elliot”. That’s definitely much better than a generic “Hello, World” program. Don’t you agree?
Step by step explanation of the above shell script
Now let’s go over the script line by line here to make sure that you understand everything.
I first included the shebang line to explicitly state that we are going to use bash shell to run this script.
Next, I ask the user to enter his/her name:
That’s just a simple echo command to print a line to the terminal; pretty self-explanatory.
Now here’s the line where all the magic happens:
Here, I used the read command to transfer the control from running script to the user, so that the user can enter a name and then store whatever user entered, in the ‘name’ variable.
Finally, the script greets the user with their name:
Notice here, you have to precede the variable name with a dollar sign to get the value stored in the variable name. If you omit the dollar sign, “Hello, name” would be displayed instead.
This dollar sign is known as the dereference operator in bash scripting.
Integers, strings or characters? How to create different variable data types in bash shell?
Let’s mess around a little bit more with the variables.
You can use the equal sign to create and set the value of a variable. For example, the following line will create a variable named age and will set its value to 27.
After you have created the age variable, you can change its value as much as you want.
The above command changes the value of the variable age from 27 to 3. If only times can go back, I can hear you saying!
Variables can hold different types of data; variables can store integers, strings, and characters.
Constant variables in bash shell
You can also create a constant variable, that is to say, a variable whose value will never change! This can be done by preceding your variable name with the readonly command:
The above command will create a constant variable PI and set its value of 3.14159. Now, you can’t’ change the value of constant variable, if you try, you will get an error:
As you can see, you can only read the value of a constant variable, but you can never change its value after it is created.
Command substitutions
The ability to store the output of a command into a variable is called command substitution and it’s by far one of the most amazing features of bash.
The date command is a classic example to demonstrate command substitution:
The above command will store the output of the command date into the variable TODAY. Notice, how you need to enclose the date command within a pair of parentheses and a dollar sign (on the left).
Alternatively, you can also enclose the command within a pair of back quotes:
The back quote method is the old way of doing command substitution, and so I highly recommend that you avoid it and stick with the modern approach:
Before you go, try turning Hello World script to a smart HelloWorld script
Now since you just learned how to do command substitution, it would make sense to visit the Hello World script one last time to perfect it!
Last time, you asked the user to enter his/her name so the script greets them; this time, you are not going to ask, your script already knows it!
Use the whoami command along with command substitution to greet whoever run the script:
As you can see, you only needed just two lines! Now run the script:
It works like a charm!
Alright, this brings us to the end of this tutorial. I hope you have enjoyed working with shell variables as much as me. Stay tuned for next week as I am going to discuss how you can pass arguments to your shell scripts.
Источник
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!
Источник