How To Set Variable In Unix
Purchase this Shell Scripting Tutorial as a PDF for just $five
4. Variables - Part I
Just about every programming language in beingness has the concept of variables - a symbolic name for a chunk of retentivity to which we can assign values, read and dispense 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 ready for u.s.a. by the environment.
Let's look dorsum at our kickoff Howdy World example. This could exist done using variables (though it's such a uncomplicated example that it doesn't really warrant it!)
Note that at that place must be no spaces around the "=" sign: VAR=value
works; VAR = value
doesn't piece of work. In the first instance, the shell sees the "=" symbol and treats the command equally a variable consignment. In the second example, the shell assumes that VAR must be the proper noun of a command and tries to execute information technology.
If you think about it, this makes sense - how else could you tell it to run the command VAR with its start statement being "=" and its second statement being "value"?
Enter the post-obit lawmaking into var.sh:
var.sh
#!/bin/sh
MY_MESSAGE = "Hello Earth"
echo $MY_MESSAGE
This assigns the string "How-do-you-do World" to the variable MY_MESSAGE
and so echo
es out the value of the variable.
Note that we need the quotes around the string Hello Earth. Whereas we could get away with echo Howdy World
because echo will take any number of parameters, a variable tin can but agree 1 value, so a cord with spaces must be quoted so that the trounce knows to treat it all as one. Otherwise, the trounce volition try to execute the control World
subsequently assigning MY_MESSAGE=Hello
The shell does non 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 lot've grown upwards with C, Pascal, or worse nonetheless 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 y'all assign a string to a variable and so try to add 1 to it, you will not get away with information technology:
$ x = "hello"
$ expr $10 + 1
expr : not - numeric statement
$
This is considering the external plan expr
just expects numbers. Simply in that location is no syntactic difference between:
MY_MESSAGE = "How-do-you-do Globe"
MY_SHORT_MESSAGE = hi
MY_NUMBER = 1
MY_PI = 3.142
MY_OTHER_PI = "3.142"
MY_MIXED = 123abc
Notation though that special characters must exist properly escaped to avert interpretation by the shell.
This is discussed farther in Chapter 6, Escape Characters.
We tin interactively set variable names using the read
command; the following script asks yous for your name and so greets yous personally:
var2.sh
#!/bin/sh
echo What is your proper name ?
read MY_NAME
echo "Hello $MY_NAME - promise you lot're well."
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. Information technology is this kind of thing which can drive a shell programmer crazy, and 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 requite it your full proper name and don't utilise double quotes around the echo
control, it still outputs correctly. How is this done? With the MY_MESSAGE
variable earlier we had to put double quotes effectually 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 demand to quote the output, of class - e.1000. echo "$MY_MESSAGE"
).
Telescopic of Variables
Variables in the Bourne shell do non take to be declared, equally they do in languages like C. Merely if you try to read an undeclared variable, the result is the empty string. Y'all become no warnings or errors. This can crusade some subtle bugs - if you assign
MY_OBFUSCATED_VARIABLE=Hullo
and and so
echo $MY_OSFUCATED_VARIABLE
And then you will get goose egg (as the second OBFUSCATED is mis-spelled).
There is a command called export
which has a fundamental result on the scope of variables. In order to really know what's going on with your variables, you will demand to understand something almost how this is used.
Create a pocket-size shell script, myvar2.sh
:
myvar2.sh
#!/bin/sh
echo "MYVAR is: $MYVAR"
MYVAR = "hi there"
echo "MYVAR is: $MYVAR"
Now run the script:
$ ./ myvar2 . sh
MYVAR is :
MYVAR is : howdy at that place
MYVAR hasn't been ready to whatever value, and then it'due south bare. Then we requite information technology a value, and it has the expected issue.
Now run:
$ MYVAR = how-do-you-do
$ ./ myvar2 . sh
MYVAR is :
MYVAR is : hi there
It'south still not been gear up! What'southward going on?!
When you phone call myvar2.sh
from your interactive shell, a new trounce is spawned to run the script. This is partly because of the #!/bin/sh
line at the outset of the script, which we discussed before.
We need to consign
the variable for it to exist inherited by another program - including a beat out script. Type:
$ export MYVAR
$ ./ myvar2 . sh
MYVAR is : hello
MYVAR is : hullo at that place
Now look at line iii of the script: this is changing the value of MYVAR
. But there is no way that this will be passed dorsum to your interactive crush. Attempt reading the value of MYVAR
:
$ repeat $MYVAR
hello
$
Once the shell script exits, its surroundings is destroyed. But MYVAR
keeps its value of hi
within your interactive shell.
In order to receive surround changes back from the script, we must source the script - this effectively runs the script within our own interactive shell, instead of spawning some other shell to run it.
Nosotros can source a script via the "." (dot) command:
$ MYVAR = hello
$ echo $MYVAR
hello
$ . ./ myvar2 . sh
MYVAR is : how-do-you-do
MYVAR is : hi there
$ echo $MYVAR
hi there
The change has now fabricated it out into our vanquish over again! This is how your .contour
or .bash_profile
file works, for case.
Annotation 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 information technology should exist. Another example of an easy mistake to make with shell scripts. One other thing worth mentioning at this point near variables, is to consider the following shell script:
#!/bin/sh
repeat "What is your name?"
read USER_NAME
repeat "Hullo $USER_NAME"
echo "I will create you a file chosen $USER_NAME_file"
touch $USER_NAME_file
Think about what result you would expect. For case, if you enter "steve" equally your USER_NAME, should the script create steve_file
?
Actually, no. This will crusade an error unless there is a variable chosen USER_NAME_file
. The crush does not know where the variable ends and the rest starts. How tin we define this?
The reply is, that we enclose the variable itself in curly brackets:
user.sh
#!/bin/sh
echo "What is your name?"
read USER_NAME
repeat "Hello $USER_NAME"
echo "I volition create you lot a file called ${USER_NAME}_file"
affect "${USER_NAME}_file"
The shell now knows that we are referring to the variable USER_NAME
and that we want it suffixed with "_file
". This can exist the downfall of many a new shell script developer, every bit the source of the trouble can be difficult to track down.
Also note the quotes around "${USER_NAME}_file"
- if the user entered "Steve Parker" (notation the space) then without the quotes, the arguments passed to affect
would be Steve
and Parker_file
- that is, we'd effectively exist saying touch Steve Parker_file
, which is ii files to be touch
ed, not i. The quotes avoid this. Thanks to Chris for highlighting this.
Back: A First Script Next: Wildcards
Books and eBooks
Contact
You lot can mail me with this course. If yous 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 existent person!
Source: https://www.shellscript.sh/variables1.html
0 Response to "How To Set Variable In Unix"
Post a Comment