Tuesday, 3 May 2011

Basic variable creation in shell

In my last article on basic shell scripting, I did the universal hello world program. This time around, I will discuss making variables.

A variable is a symbolic name for information. You can call a variable nearly anything in unix shell scripting. There are some exceptions though. Here is the simple program outlining variables:

#!/usr/bin/sh

salutation=Hi;
name=Fred;

echo $salutation $name;
echo "";
echo salutation name;

The first line describes this program as a shell script. The second line assigns the value of "Hi" to the variable of salutation. The third line assigned the value of "Fred" to the variable of name. The forth line outputs the two variable values. This is done by using the "$" in front of the variable name. The fifth line prints out a blank line. The sixth line is only for comparison of what the fourth line would have looked like if it did not have the "$". I have saved the contents of the file to a file called "test.sh" and made it executable. The output is:

$ ./test.sh
Hi Fred

salutation name

That is as easy as variables can get. You can store text and letters in variables, as well as strings. With some clever delimiting, you can also turn these variables into mini lists - similar to arrays in other more advanced forms of programming.

I will attempt to write up how to do some basic comparisons in my next article on scripting. I am also welcome to suggestions via the comments of this post.

No comments:

Post a Comment