Everything Shell Script

  • Home
  • Home

Saturday, 8 October 2016

Variables in Shell Script - Part 1

 Niraj Bhagchandani     07:25:00     No comments   

 
Every Programming language in existence has the concepts of variable – It can be termed as a chunk of memory which can be assigned values, read and manipute its contents. Thus, Bourne Shell aslo introduces the idea of variables. The explanation of variables is described in two different parts.
Let us look back to our First Shell Program for example which can be done easily using variables.

Please Note:

Pre-requisite: There should not be spaces around the “=” sign i.e. VARIABLE=value works but in shell scritp VARIABLE = value does not work efficiently. ( and gives command not found error ). This is because in the first case the, when the shell sees “=” symbol it treats as a variable assignment, while in the later case it assumes that VARIABLE must be the name of the command.



Enter the following code into variable1.sh:

variable1.sh
#!/bin/sh
MESSAGE="Hello World"
echo $MESSAGE
 

The above program assigns “Hello World” as a string to store into
the variable MESSAGE then echoes out the value in the
second line of the code. 


Please Note:
We need to the quotes around the string Hello World.Whereas, we could get away with ehco Hello World because echo will take any number of parameters while variable can hold only one value, also a string with spaces must be quoted as an indicatoin to treat all as one. Otherwise, the shell will try to execute World as a command after assigning MESSAGE=Hello
Also, do note that shell does not care about data types such as strings, integers, real numbers etc.
The reality is, they are stored as strings, but routines may treat strings as a number if these numbers are stored as described. For example if you assign a string to a variable then try to add 1 to it, you shall not get away with correct output as described.


sh-4.2$ x="string"
sh-4.2$ expr $x + 1
expr: non-numeric argument
sh-4.2$
 
The above output is as exptected because there is no much difference in their syntax.
 
sh-4.2$ MESSAGE="My Message" 
sh-4.2$ SHORT_MESSAGE=hi
sh-4.2$ NUMBER=3
sh-4.2$ PI=3.142
sh-4.2$ OTHER_PI="3.142"
sh-4.2$ MIXED=456xyz


To get the values from user just like printf() function in C, we can interactively set variable names using read command; for Example:

variable2.sh
 
#!/bin/sh
echo What is your age?
read age
echo "Hello friends! My age is $age."
echo ‘Hello friends! My age is $age.’

The above code will work differently while echoing with double quotes and singe quotes. Here, in Double quotes string the value of $age is printed, while in the later case (i.e. string with single quotes) the $age is printed as a string, thus the value of $age is not echoed out during execution of shell script.

Scope of Variables

The variables in C language are declared in much different way then in Bourne Shell. But if you try to read an undeclared variable, the result will always stay empty string, thus you will not get any warnings or errors. This may cause some bugs in your assignments.
Example:

sh-4.2$ HOME=/opt/lampp
and then if you type
sh-4.2$ echo $HME;

it will output empty string rather than error or warning.
Okay, friends now let us understand variables in more detail in order to really know what’s going on with variables. You will need to understand something about how this is used.
Let us create a simple script.

variable3.sh
 
#!/bin/sh
echo "VARIABLE is: $VARIABLE"
VARIABLE="hi there"
echo "VARIABLE is: VARIABLE"

Let us run the script:
sh-4.2$ ./VARIABLE.sh
VARIABLE is:
VARIABLE is: hi there

VARIABLE does not contain any value intially so, it prints empty string. Then we assign it a value, and it has the expected result.
Okay, if you understood the above program easily then let us see the next part of variable. Let us see the sequence given below.
Now run:
 
sh-4.2$ VARIABLE=hello
sh-4.2$ ./variable3.sh
VARIABLE is:
VARIABLE is: hi there
 

Ops! Something went wrong, though we have assigned the variable
(VARIABLE) in the shell it prints an empty string.  So, now let us
understand the core concept behind this.
When you call variable4.sh from shell interactively, a new shell gets started to run the script. This is partly because #!/bin/sh line is at the start of the script which we have discussed earlier.
So, to overcome the above issue there is a command callled export which has the fundamental effect on the scope of variables. Now, Let us see how export would be useful in generating output.

Example:
 
sh-4.2$ export VARIABLE
sh-4.2$ ./variable3.sh
VARIABLE is: hello
VARIABLE is: hi there

Okay, there it is you can view the line 3 of the script: the value of VARIABLE has not been changed. But, it might not pass the value interactively back to the shell.
Let us try to read the value of VARIABLE.

sh-4.2$ echo $VARIABLE
hello
sh-4.2$

Keep in mind that once the shell script exists, the shell environment is destroyed. But VARIABLE keeps its value as hello within its 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:

variable3.sh
 
sh-4.2$ VARIABLE=hello
sh-4.2$ echo $VARIABLE
hello
sh-4.2$ . ./variable3.sh
VARIABLE is: hello
VARIABLE is: hi there
$ echo $VARIABLE
hi there

In realiuty, it has now made the change into our shell! The best example for this is .profile and .bash_profile file. So, if you define variable in these files, then there is no need to export a variable.
Now, Let us see the common mistake that we make during the shell script. Let us monitor the shell script variable and point out its values as:

variable4.sh
 
#!/bin/sh
echo "Please provide Category name to create file: "
read CATEGORY
echo "This is the category: $CATEGORY"
echo "Let us create a file named: $CATEGORY_file"
touch $CATEGORY_file
 
Let us analyze the code here for a moment and we enter category as “shoes” as CATEGORY, then the last line of the code should actually create a file named shoes_file (here touch command is used to create a file).

Thus, the answer is a big NO. It will not create a file but instead it will give you an error as it understand $CATEGORY_file as an entire variable rather than $CATEGORY as variable and _file as a string. So, How do we define the above mentioned thing in here?

The answer to this question is as follows: we declare the variable itself in curly brackets:

category.sh
 
#!/bin/sh
echo "Please provide Category name to create file: "
read CATEGORY
echo "This is the category: $CATEGORY"
echo "Let us create a file named: ${CATEGORY}_file"
touch ${CATEGORY}_file

Thus, the above code will refer to the variable CATEGORY and that suffix which we want as “_file”.
Note:
the quotes around “${CATEGORY}_file” -- If the user enters “Tooth Brush” (with the space within) then without the quotes, the argument passed to touch command would be Tooth and Brush_file – i.e. the command would be
touch Tooth Brush_file
thus it will create 2 files instead of one.

Program Link : https://goo.gl/kQGhnM

In my next tutorial I would cover more about variables in shell script

Regards, 
Niraj Bhagchandani 
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Email ThisBlogThis!Share to XShare to Facebook
Newer Post Older Post Home

0 comments:

Post a Comment

Amazon Ads

Popular Posts

  • 12 differnet examples of For Loop in Shell Script
    The Link to programs given in this tutorial is:  https://goo.gl/akbcTw Well, to begin with FOR LOOP, I would tell that there are 2 diff...
  • Powerline – Adds Powerful Statuslines and Prompts to Vim Editor and Bash Terminal
    Powerline is a great statusline plugin for Vim editor , which is developed in Python and provides statuslines and prompts for many other...
  • How to install Docker and run Docker containers on Linux Mint 18/18.1
         How to install Docker and run Docker containers on Linux Mint 18/18.1 So, now before going through all the steps update and upg...
  • While Loop in Shell Script
    To run the given example live online please visit the following link: https://goo.gl/mD69Gj There are basic loops in shell script. For ...
  • Until Loop in Shell Script.
    To run these programs online I request you to go to following link: https://goo.gl/xKheU3 The until loop is similar to while loop in shel...
  • Variables in Shell Script - Part 1
      Every Programming language in existence has the concepts of variable – It can be termed as a chunk of memory which can be assigned valu...
  • Escape character in Shell Script
    Okay!! uptil now we have seen a lot of stuffs regarding Shell Script. But how about escape characters Example: What if you want to displa...
  • Wildcards
     A wildcard is a character that can be used as a substitute for any of a class of characters in a search, thereby greatly increasin...
  • My First Shell Script.
    My First Shell script We are about to write a script for Hello World. After that we will have some flavors of Hello World Program. Fir...

Recent Posts

Categories

  • Docker in Mint 18.1
  • Docker Linux Mint
  • Install Docker
  • Install Docker in Mint 18
  • Install Docker Linux Mint
  • tecmint

Pages

  • Home

Text Widget

Blog Archive

  • ►  2017 (1)
    • ►  June (1)
  • ▼  2016 (8)
    • ►  November (1)
    • ▼  October (7)
      • Until Loop in Shell Script.
      • While Loop in Shell Script
      • 12 differnet examples of For Loop in Shell Script
      • Escape character in Shell Script
      • Wildcards
      • Variables in Shell Script - Part 1
      • My First Shell Script.

Page Views:

About Me

Niraj Bhagchandani
View my complete profile

Search Here:

Powered by Blogger.

Sample Text

Copyright © Everything Shell Script | Powered by Blogger
Design by Hardeep Asrani | Blogger Theme by NewBloggerThemes.com | Distributed By Gooyaabi Templates