Introduction to Shell Programming

0% found this document useful (0 votes)
71 views4 pages
A shell is a program that acts as an interface between the user and the Linux operating system, allowing users to enter commands. The standard shell in Linux is bash. Shell scripts can be cr…

Uploaded by

Meenal Sinha
  • What is a command shell?
  • Making a Script Executable
  • Conditions
  • Control Structures
  • Assignment

What is a command shell?

A shell is a program that acts as the interface between you and the Linux system, enabling you to
enter commands for the operating system to execute. In that respect, it resembles the Windows
command prompt, but as mentioned earlier, Linux shells are much more powerful.

On Linux, the standard shell that is always installed as /bin/sh is called bash (the GNU Bourne-
Again Shell), from the GNU suite of tools.
You can check the version of bash you have with the following command:
$ /bin/bash –version
Many other shells are available, either free or commercially. The following table offers a brief
summary of some of the more common shells available:

Creating a shell script:


Using any text editor, you need to create a file containing the commands; create a file called
[Link] that looks like this:

myvar=”Hi there”
echo $myvar
echo “$myvar”
echo ‘$myvar’
echo \$myvar
echo Enter some text
read myvar
echo ‘$myvar’ now equals $myvar
exit 0
Making a Script Executable
Now that you have your script file, you can run it in two ways. The simpler way is to invoke the
shell with the name of the script file as a parameter:
$ /bin/sh first
Or
$ chmod +x first
Then $ first

Environment Variables

A sample programme to manipulate the environment variable: [Link]


salutation=”Hello”
echo $salutation
echo “The program $0 is now running”
echo “The second parameter was $2”
echo “The first parameter was $1”
echo “The parameter list was $*“
echo “The user’s home directory is $HOME”
echo “Please enter a new greeting”
read salutation
echo $salutation
echo “The script is now complete”
exit 0

If you run this script, you get the following output:


$ ./test2_var foo bar baz
Hello
The program ./test is now running
The second parameter was bar
The first parameter was foo
The parameter list was foo bar baz
The user’s home directory is /home/userid
Please enter a new greeting
Sire
Sire
The script is now complete
$
Conditions
You can also write it like this:
if [ condition ]
then
...
Fi

Control Structures
if
The if statement is very simple: It tests the result of a command and then conditionally executes
a
group of statements:
if condition
then
statements
else
statements
fi
Sample programme: [Link]
echo “Is it morning? Please answer yes or no”
read timeofday
if [ $timeofday = “yes” ]; then
echo “Good morning”
else
echo “Good afternoon”
fi
exit 0
elif
Unfortunately, there are several problems with this very simple script. For one thing, it will take
any answer except yes as meaning no. You can prevent this by using the elif construct, which
allows you to add a second condition to be checked when the else portion of the if is executed.
You can modify the previous script so that it reports an error message if the user types in
anything other than yes or no. Do this by replacing the else with elif and then adding another
condition:
#!/bin/sh
echo “Is it morning? Please answer yes or no”
read timeofday
if [ $timeofday = “yes” ]
then
echo “Good morning”
elif [ $timeofday = “no” ]; then
echo “Good afternoon”
else
echo “Sorry, $timeofday not recognized. Enter yes or no”
exit 1
fi
exit 0

Assignment9:
Write a shell script to print the following number pattern (using nested for loop).
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
Assignment10:
Write a shell script to print the prime numbers between n & m. [n & m are user input] (using nested
while loop).

Reference:
Beginning Linux Programming by NEIL MATTHEW published by SPD

Common questions

Powered by AI

An 'if' statement in a shell script tests the result of a command and conditionally executes a series of statements. The logical flow begins with 'if condition', followed by 'then' and the commands to execute if true. An 'else' clause can specify commands for when the condition is false. An example is the 'test3.sh' script, where user input determines a greeting, such as 'Good morning' or 'Good afternoon'. An 'elif' allows for additional conditions, as shown in a script modification that checks for both 'yes' and 'no', rejecting unrecognized inputs .

To create a shell script for printing a number pattern using nested loops, one must initialize an outer loop to iterate through numbers delineating how many times each row is printed (1 to n), and an inner loop to control repeating numbers on each line. Challenges include correctly managing the loop counters and ensuring correct formatting for incremental numbers. Creating such scripts requires understanding nested loop structures in shell scripting environments .

Bash, as the default Linux shell, offers comprehensive scripting capabilities, extensive user community support, and compatibility with various scripts due to its GNU foundation. However, limitations may include slower execution speed for built-in commands compared to more specialized shells, limited features in comparison to newer shells like zsh that offer improved enhancements such as better auto-completion. Performance in heavy scripting contexts might necessitate using other optimized shells .

Essential programming constructs for shell scripts managing environment variables and demonstrating conditional logic include 'variable assignment', 'echo' for output, 'if', 'elif', and 'else' for control flow, and 'read' for user input. The script 'test2.sh' illustrates using these: variables are set and output; the script captures user input to modify variables; and conditional constructs dictate script execution based on input, demonstrating environmental and logical control .

The 'elif' construct enhances shell scripts by allowing multiple conditions to be evaluated sequentially, solving the issue of scripts interpreting any non-matching initial condition as false. The enhancement is applied by adding 'elif [ condition ]; then' between 'if' and 'else' statements. This is utilized in the modified morning/evening script, which reports an error if the user input is not 'yes' or 'no', thus preventing unintended responses .

A command shell in a Linux system acts as the interface between the user and the Linux system, allowing users to enter commands to be executed by the operating system. It is considered more powerful than the Windows command prompt because Linux shells, such as the GNU Bourne-Again Shell (bash), offer advanced capabilities for scripting, automation, and environment control, making them essential tools for system administration and development tasks .

A shell script can find prime numbers between two numbers using nested 'while' loops wherein the outer 'while' loops track the current number, and the inner checks divisibility using modulo operation to confirm primality. Algorithmic considerations include optimizing divisibility checks to half the current number or using the square root, ensuring efficient execution. Handling edge cases like 'n' or 'm' being less than two, where there are no primes, is also critical .

Environment variables in shell scripts store data that can be used and controlled by the script, allowing for dynamic data handling. They are accessed via a dollar sign ('$') prefix. An example of their use is in the 'test2.sh' script, where the variable 'salutation' is initialized and its value is output. The script captures a new value from user input, demonstrating manipulation. It also accesses built-in variables like '$HOME' to reach the user's home directory, showcasing environment querying .

To make a shell script executable in Linux, you must change its file permissions to grant execution rights using the command 'chmod +x'. Once executable, the script can be run by invoking the shell with the script file name as a parameter, such as '/bin/sh first', or by typing the script's name directly if it is in a directory specified in the system's PATH, e.g., '$ first' .

Shell scripts handle user input using the 'read' command, storing input in variables for further processing. Techniques for input validation include using 'if', 'elif', and 'else' conditions to ensure data meets expected formats or values, along with regular expressions for more complex validation needs. Error handling commands, such as providing feedback or requiring re-entry, also promote robustness .

What is a command shell? 
A shell is a program that acts as the interface between you and the Linux system, enabling you to
echo ‘$myvar’ now equals $myvar 
exit 0 
Making a Script Executable 
Now that you have your script file, you can run it in tw
The program ./test is now running 
The second parameter was bar 
The first parameter was foo 
The parameter list was foo bar
if condition 
then 
statements 
else 
statements 
fi 
Sample programme: test3.sh 
echo “Is it morning? Please answer yes or n

You might also like