• No results found

Shell Script

In document Std11-CompSci-EM-2.pdf (Page 179-187)

WINDOWS EXPLORER

II. State whether the following statements are True or False 1 . In Windows XP two files in the same folder can have the same

4. Suitable to any machine: Suitable Linux version can run on any machine available now. This allows low investment for the hardware

3.10 Shell Script

A shell script is a text file that contains Linux commands. You can create a file by using any of the standard editors such as Vi editor (which you are going to study at the end of the chapter). Suppose you want to repeatedly execute a set of Linux commands, in the same order then you will seek the help of shell script. Entering the commands in the command line sequentially is not only a frustrating job, but also an exacting one. Either you may commit mistakes in spelling or you may change the order of the commands. In either case, you will run into difficulties. A shell script is handy in these circumstances because you have to enter the command only once. Shell scripts allow input/output operations and manipulation of variables.

Executing a Shell Script

When you Logon to the Linux system, you get a copy of the shell to work with. This shell is known as the Login shell. Your default shell is BASH shell. The BASH shell has the capabilities of the programming languages. You can create complex shell programs with its capabilities.

A shell program combines Linux commands to solve the given problems. The Linux shell provides many of the tools found in C language. You can create variables and assign them values. You can also create variables in a script file, which can be assigned values interactively by the users. By giving sh command in the command prompt, a new shell is created. This new shell is known as the sub-shell or the child shell of the current shell, which can be used to execute a shell script. The shell script is passed to the child shell for execution.

This arrangement makes the Login shell impervious to the whims and fancies of the user. If any undesirable event happens, only the child shell is affected and that may be deleted immediately without causing any damage to the Login shell.

You should create the shell script carefully. When you create a file, you will have the read and write privileges but you will not be granted execute permission automatically. Even with these limited capabilities you can run the shell program with either of the following commands in the command prompt.

$ sh file_name

$ . file_name

If you want to run a shell script directly at the $ prompt, you can change the File Access Permission (FAP) of the specified shell script by granting the execute permission. This can be achieved by chmod command. Suppose you want to run the edufile directly from the $ prompt the following commands should be given.

$ chmod u+x edufile $ edufile

+x command in tandem with chmod gives the execute permission to any user. The u+x command gives the owner of the file the execute

permission. When you execute the above shell script, the current shell creates a new shell and executes the script in the newly created shell.

3.11 Variables

Variables are placeholders to store values. All Linux variables are treated as character strings. This may seem that you cannot do any mathematical operations with those variables. However, this limitation can be overcome by expr and let commands.

Creating Variables

As already stated, the BASH shell is your default shell; you have to do your work in BASH shell only, unless you desire to change to some other shell. The variable created within a shell is called a shell variable.

Variables can be created as and when the user wants to create them by simple assignment of values. A variable can be created without a value being assigned to it by leaving the right-hand side including the assignment operator.

The variable name in shell script may consist of alphabetic characters, the underscore and a number.

It can not include the exclamation mark (!), the ampersand (&) or the blank space.

The number should not be the first character.

It should not be of unreasonable length.

Command names should not be used as variable names.

Valid script variable names: file1, bookshell, book_shell, a+b, rs-paise Invalid script variable names: a + b, a+ b, a!b, ab&, a=b.

The syntax for creating a variable is given below:

<variable_name>=<value>

Note: When declaring a variable, there must be no space on either side of the assignment operator (=). It is like the assignment statement of C programming. If you leave blank space before and after the “=”

operator it is like “==” (equality) operator of C programming.

If the value being assigned contains any delimiters (such as embedded spaces), then it should be enclosed within either single or double quotes.

From the above statement it may seem that single quote and double quotes can be used interchangeably. But, there is a subtle difference, which you will see later.

Example:

name= “Ezhil kumaran”

You can also write the above command as Name=‘Ezhil Kumaran’

If the value does not have spaces, the quotes are optional.

Example:

In the above assignment, the variable number, though in the form of the number, it is not a numeric value. It is a character string. Therefore, the variable number contains the character ‘1’ and ‘2’ not the number 12 = 1100 in binary form. So, you cannot do fundamental operations of algebra, that is, you cannot add, subtract, multiply or divide.

Referencing Variables

The $ symbol is used to refer the contents of a variable. The $ sign extracts the contents of the variable following it. Consider the example

var1=${var2}. The variables var1 and var2 refer to the memory locations.

${var2} command extracts the value found in that location. The copy of the obtained value from that location is stored in var1. The braces are optional. But, if you want to concatenate the contents of one variable with another value, the braces are essential. For example the variable father contains the value John and if you want to add son to John and store the result in son1 variable, you should give the following command

$ son1=${father}son

then the contents son1 will be Johnson.

What will happen if you omit the braces? The result is obvious. Without braces the command will be

$ son1=$fatherson

The first $ is the prompt and the second $ is the reference operator.

Since there is no blank space in between father and son, fatherson will be taken as a variable, and if such variable does not exist, you will get one type of error. Unfortunately if that variable exits then that value will be assigned without any warning .The result is an unpleasant surprise (If you leave a blank space in between father and son the variable will be rejected).

Reading a Value into a Variable

If you want to get the name from the user, you should enter

“please enter name ”

Then you should make arrangements to store the entered name into the memory.

The above can be written in Linux as follows.

echo “ Please enter your name”

read name

The echo command simply prints the string on the screen. This serves as a prompt for the user. The read command, on execution, waits for the user to enter a value for the variable. When the user presses the

<Enter> key, after entering the value, the remaining part of the shell script, if any, is executed.

The response of the user is caught into the variable name (called) name. The read command can be used at the shell prompt, but is usually used in shell scripts.

Note: As already stated, the double quotes (“”) improve the readability.

3.12 Expressions

The expr and let Commands

For any individual, a day hardly ends up without doing any arithmetic calculation. Can you imagine a world without arithmetical calculations?

The answer is an emphatic “no”. Most shells do not support numeric variables. All variables are treated as character strings. However, to program in the shell, it is imperative that you will be able to mathematically manipulate variables. This is possible by the use of the expr and let commands. The expr command is used to evaluate arithmetic expressions. The output of this command is sent to the standard output (screen).

Example:

$ expr 21 + 51

will display 72 on the screen. Note that there must be a space on either side of the operator (+). Variables can be used in the expr command such as

$ num1=7

$ num2=3

$ expr $num1 + $num2

Since output is sent to the screen, the value 10 is displayed on the screen. Remember $ when it is not used as the user prompt, is used to refer the value of the variable.

Therefore $num1 is replaced by character ‘7’ and $num2 is replaced by character ‘3’. The command expr then converts these characters into numbers and the addition is done afterwards.

The expr command supports +, -, *, and /. But you should be careful when using the * operator. Since * is used for wildcard character, it should be distinguished for multiplication operation. If you write \*, then this will be treated as multiplicative operator.

$ expr 1 / 2 and will display 0 and not 0.5. Please note the blank space before and after the / sign. What will happen if you give the following command?

$ expr 0.5 / 2

What you get is an error message. Since the decimal point will be treated as dot, 0.5 will not even be treated as a number.

The command let lets you do arithmetic calculation and compare two values. The syntax for let is

$ let <value1><operator><value2>

Here the operator stands for either the arithmetic or the relational operator. The command let is an improvement over expr. The command let evaluates any variable and converts its value into an arithmetic variable. This capability is utilized in shell script to manage control structures. While expr needs blank space/spaces before and after the operator, the command let demands no blank space/spaces either before or after the operator. If you want to leave blank space/spaces then you can do so by enclosing the entire expression within quotes. If you do not assign the result of an operation of the let command, the result is displayed on the screen.

Example:

$ let pr=5*10

echo “The product is $pr”

The product is 50

Note: The operator * (multiplication) should not be entered as \*.

Note : Unlike expr , let should have variable name in the left hand side of assignment operator.

If you want to leave blank space/spaces before and after the operator, you should enclose the entire operation within quotes.

Example:

$ let “ pr = 5 * 10 ” echo “The product is $pr”

The product is 50

Suppose you assign, the result of an operation to a variable, the result will not be displayed on the screen, whereas the result is assigned to the variable. If you want to see the result on the screen you should use the echo command.

Example:

$ let “ sum = 2 + 4 ”

$ echo “The sum is $sum”

The sum is 6

The following assignments are also possible in script programming by using the let command as follows.

let a=0 let a=a+1

Note: Alas, let also fails with decimal numbers such as 2.3, 0.5 etc..

You were told that there is subtle difference between single quotes and double quotes. You will now see that difference. The variable name contains Ilamathi. Suppose you give the following commands

echo “The given name is $name”

echo ‘The given name is $name’

what you see on the screen are The given name is Ilamathi The given name is $name

Double quotes actually references the variable. $name is replaced by its contents namely by Ilamathi. But single quote, simply reproduces whatever is found within it. That is, $name is reproduced as such.

In document Std11-CompSci-EM-2.pdf (Page 179-187)

Related documents