Document Details

StylishSpessartine

Uploaded by StylishSpessartine

University of Science and Technology

2024

Tags

shell scripting linux commands computer science

Full Transcript

**University of Science and Technology** **Faculty of Computer Science and Information Technology** **Open Source Operating Systems** **Lab (8) Date 06-05-2024** **[Shell Scripts]** **Description:** The students take from this exercise how to write shell scripts that uses sequence of linux com...

**University of Science and Technology** **Faculty of Computer Science and Information Technology** **Open Source Operating Systems** **Lab (8) Date 06-05-2024** **[Shell Scripts]** **Description:** The students take from this exercise how to write shell scripts that uses sequence of linux commands for various purposes using basic input and output functions and control statements. **Lab Learning Outcomes:** Writing Shell scripts to interact with the Operating Systems and for user operations. **Lab Instructions:** The lab instructor has to follow the steps below to demonstrate to the students the following: 1. **What is a shell script?** - The shell script is an executable text file that guides the shell into performing a sequence of actions. - Begin Every shell script with a comment that specifies the interpreter, which should run the script. \#!/bin/bash\ \#!/bin/csh\ \#!/bin/tcsh 2. **How to write a shell script?** 1. Choose a good name for your script. 2. Create the script using your favorite editor. To write a shell script program we use as set of: -Comments (beginning with \#) -commands (linux commands) -Variables (local, environment, string, number...) -program control ( if, elif, else, while , case ,....) -Functions 3- Make the file executable by using chmod command.\ The script file must also be executable. We will use permission 745, or alternatively 755.\ 4- Running Scripts\ assume that we save the previous script under the name **start**. After changing the permissions of the file **start** to 745 (using chmod), we can execute this script by entering **. /start**. The start script outputs information to your terminal window. **Example1:** Write a shell script to display name and address 1. Choose a good name for your script. (address) 2. Create the script using your favorite editor. To write a shell script \$ vi address 3. press esc key press i key 4. write the program : echo "Mohammed Ali" echo "UST" echo "College of Computer Science" echo "Sudan, Omdurman" 5. to save and exit press esc key :wq 6. Make the file executable. \$ chmod700 address.sh 7. Running Scripts\ \$./address.sh **Example2:** The following commands copies all files into a directory, and then deletes the directory along with its contents. \$ mkdir trash \$ cp \* trash \$ rm --rf trash \$ mkdir trash Instead of having to type all that interactively on the shell, write a shell program instead.(follow the above steps in example 1 to write and execute the script). \$ vi trash \#!/bin/bash \# this script deletes some files cp \* trash rm -rf trash mkdir trash echo "Deleted all files!" 8. **INPUT AND OUTPUT:** **\* Output with echo:**\ We have already seen the output statement, echo. The **echo** statement is supplied a list of items to output. These items are a combination of literal values, treated as strings, variables (with the \$ preceding their names), and Linux commands placed inside \` \` or \$() marks. You cannot use the expr statement though in this way.\ Here are some examples of output statements. Assume that any variable listed actually has a value stored in it.\ echo Hello \$NAME, how are you?\ echo Your current directory is \$PWD, your home is \$HOME\ echo Your current directory is 'pwd', your home is \~\ echo The date and time are \$(date)\ The echo statement also permits a number of "escape" characters. These are characters preceded by a back slash (\\). You must force echo to interpret these characters, if present. This is done through the --e option. The sequence including any literal characters that go with the escape characters must be placed within "" marks. **Here are some examples of escape characters and what they output:\ **\$ echo --e \"Hello World! \\nHow are you today?\"\ Hello World\ How are you today?\ \$ echo --e \"January\\tFebruary\\tMarch\\tApril\"\ January February March April\ \$ echo --e Hello\\\\World\ Hello\\World (recall that the quote marks are not needed for \\\\) The use of "" and '' in echo statements is slightly different from their use in assignment statement. As we see below, the quote marks appear to do the same thing as we saw with assignment statements. The "" return values of variables and Linux commands whereas in '', everything is treated literally. **Example:** Assume **FIRST** stores Frank and **LAST** stores Zappa.\ \$ echo \$FIRST \$LAST\ **output:** Frank Zappa\ \$ echo \"\$FIRST \$LAST\"\ **output:** Frank Zappa\ \$ echo \'\$FIRST \$LAST\'\ **output:** \$FIRST \$LAST\ \$ echo \"\$FIRST \\n\$LAST\"\ **output:** Frank \\n Zappa **\* Input with read**:\ The input statement is **read**. The read statement is then followed by one or more variables. If multiple variables are specified, they must be separated by spaces. The variable names are listed without \$ preceding them. The read can be used to input any number of variable values. The following are some examples of read statements:\ \$ read FIRST\ \$ read FIRST LAST\ \$ read x y z\ There are two ways to accomplish this. The first is through an echo statement preceding the input statement. For instance, we might use:\ \$ echo Enter your name\ \$ read NAME\ With this notation, the echo statement's output would appear and the cursor would then move to a new line so that the terminal window might look like the following.\ **Enter your name Ali**\ the --n option for echo causes the output to not conclude with a new line. If we modify the echo statement to use --n, then when we run the program, the prompting message and the text appear on the same line.. **Example1:** **echo --n Enter your name\ read NAME** \#!/bin/bash echo "Enter your student number " read NO echo \$NO **Example2**: Write an interactive shell script to read input and display output : vi ipop press esc key press i key echo What is your name? read name echo My name is \$name press esc key :wq 9. **Shell Scripts Examples:** - **using the basic commands // Enter data from (keyboard)** vi directory press esc key press i key echo "enter directory name" read Dir mkdir \$Dir echo "directory is maked " - Environmental Variables vi ENV press esc key press i key \#!/bin/bash \#using variables echo "user is login \$USER" echo "the home directory is \$HOME" echo " the shell is use =\$SHELL" - **create files and directory** vi ENV press esc key press i key \#!/bin/bash Dir=\$1 File=\$2 mkdir \$Dir echo "directory is maked " touch \$File echo "file is created" echo \$0 //shell script name echo \$\# //Number of Arguments echo \$\* //Arguments values echo \$? // check the error - **Script to test MY knowledge about variables!** vi Know press esc key press i key \#!/bin/bash myname=Vivek myos = TroubleOS myno=5 echo \"My name is \$myname\" echo \"My os is \$myos\" echo \"My number is \$myno, can you see this number\" 10. **Special Shell Variables:** There are many special shell variables that are set automatically by the shell. Some of these can not be changed by the user. - **Positional parameters:** These are shell variables that correspond to the shell arguments. The following list shows positional parameters: +-----------------------------------+-----------------------------------+ | \* | **\$0** | | | | | | The filename of the current | | | script. | +===================================+===================================+ | \* | **\$n** | | | | | | These variables correspond to the | | | arguments with which a script was | | | invoked. Here **n** is a positive | | | decimal number corresponding to | | | the position of an argument (the | | | first argument is \$1, the second | | | argument is \$2, and so on). | +-----------------------------------+-----------------------------------+ | \* | **\$\#** | | | | | | The number of arguments supplied | | | to a script. | +-----------------------------------+-----------------------------------+ | \* | **\$\*** | | | | | | All the arguments are double | | | quoted. If a script receives two | | | arguments, \$\* is equivalent to | | | \$1 \$2. | +-----------------------------------+-----------------------------------+ | \* | **\$@** | | | | | | All the arguments are | | | individually double quoted. If a | | | script receives two arguments, | | | \$@ is equivalent to \$1 \$2. | +-----------------------------------+-----------------------------------+ | \* | **\$?** | | | | | | The exit status of the last | | | command executed. | +-----------------------------------+-----------------------------------+ | \* | **\$\$** | | | | | | The process number of the current | | | shell. For shell scripts, this is | | | the process ID under which they | | | are executing. | +-----------------------------------+-----------------------------------+ | \* | **\$!** | | | | | | The process number of the last | | | background command. | +-----------------------------------+-----------------------------------+ - Command-Line Arguments: ----------------------- The command-line arguments \$1, \$2, \$3, \...\$9 are positional parameters, with \$0 pointing to the actual command, program, shell script, or function and \$1, \$2, \$3, \...\$9 as the arguments to the command. Following script uses various special variables related to the command line − \#!/bin/bash echo \"File Name: \$0\" echo \"First Parameter : \$1\" echo \"Second Parameter : \$2\" echo \"Quoted Values: \$@\" echo \"Quoted Values: \$\*\" echo \"Total Number of Parameters : \$\#\" Here is a sample run for the above script − \$./test.sh Zara Ali File Name :./test.sh First Parameter : Zara Second Parameter : Ali Quoted Values: Zara Ali Quoted Values: Zara Ali Total Number of Parameters : 2 11. **Arithmetic operators:** Expr is used to perform arithmetic operations. **Syntax***:* expr op1 math-operator op2 **Example1:** \$ expr 1 + 3 \$ expr 2 - 1 \$ expr 10 / 2 \$ expr 20 % 3 \$ expr 10 \\\* 3 \$ echo \`expr 6 + 3\` **Note**: - expr 20 %3 - Remainder read as 20 mod 3 and remainder is 2. - expr 10 \\\* 3 - Multiplication use \\\* and not \* since its wild card. - First, before expr keyword we used \` (back quote) sign not the (single quote i.e. \') sign. Back quote is - Second, expr is also end with \` i.e. back quote. - Here expr 6 + 3 is evaluated to 9, then echo command prints 9 as sum - Here if you use double quote or single quote, it will NOT work echo \"expr 6 + 3\" \# It will print expr 6 + 3 echo \'expr 6 + 3\' \# It will print expr 6 + 3 **Example2: \$vi test** \#!/bin/bash \# using expr keyword and basic command echo " enter the string " read Str Length=\`echo \$Str \| wc --c \` Len\_str=\`expr \$length -- 1\` echo "the length=Slen\_str" Here is a sample run for the above script − \$./test.sh nameisZaraAli **Example3:** \#!/bin/bash val=\`expr 2 + 2\` echo \"Total value : \$val\" The above script will generate the following result : \*Total value : 4 The following points need to be considered while adding − - There must be spaces between operators and expressions. For example, 2+2 is not correct; it should be written as 2 + 2. - The complete expression should be enclosed between ' ', called the backtick. **Example4**: Write a shell script to do addition of given five numbers in command line argument? \# ADDITION OF FIVE NUMBERS PROGRAM vi fadd press esc key press i key tput clear echo "Program to add five numbers" a=\`expr \$1 + \$2 + \$3 + \$4 + \$5\` echo " The sum of given numbers are " \$a INPUT & OUTPUT: \$./ add.sh 33 44 55 66 77 The sum of the given numbers is 275 12. **shell arrays:** A shell variable is capable enough to hold a single value. These variables are called scalar variables. Shell supports a different type of variable called an array variable. This can hold multiple values at the same time. Arrays provide a method of grouping a set of variables. Instead of creating a new name for each variable that is required, you can use a single array variable that stores all the other variables. All the naming rules discussed for Shell Variables would be applicable while naming arrays. - Defining Array Values: ---------------------- The difference between an array variable and a scalar variable can be explained as follows. Suppose you are trying to represent the names of various students as a set of variables. Each of the individual variables is a scalar variable as follows − NAME01=\"Zara\" NAME02=\"Qadir\" NAME03=\"Mahnaz\" NAME04=\"Ayan\" NAME05=\"Daisy\" We can use a single array to store all the above mentioned names. Following is the simplest method of creating an array variable. This helps assign a value to one of its indices. array\_name\[index\]=value Here array\_name is the name of the array, index is the index of the item in the array that you want to set, and value is the value you want to set for that item. As an example, the following commands − NAME\[0\]=\"Zara\" NAME\[1\]=\"Qadir\" NAME\[2\]=\"Mahnaz\" NAME\[3\]=\"Ayan\" NAME\[4\]=\"Daisy\" - Accessing Array Values: ----------------------- After you have set any array variable, you access it as follows − \${array\_name\[index\]} Here array\_name is the name of the array, and index is the index of the value to be accessed. Following is an example to understand the concept − \#!/bin/sh NAME\[0\]=\"Zara\" NAME\[1\]=\"Qadir\" NAME\[2\]=\"Mahnaz\" NAME\[3\]=\"Ayan\" NAME\[4\]=\"Daisy\" echo \"First Index: \${NAME\[0\]}\" echo \"Second Index: \${NAME\[1\]}\" The above example will generate the following result − \$./test.sh First Index: Zara Second Index: Qadir You can access all the items in an array in one of the following ways − \${array\_name\[\*\]} \${array\_name\[@\]} Here array\_name is the name of the array you are interested in. Following example will help you understand the concept -- \#!/bin/sh NAME\[0\]=\"Zara\" NAME\[1\]=\"Qadir\" NAME\[2\]=\"Mahnaz\" NAME\[3\]=\"Ayan\" NAME\[4\]=\"Daisy\" echo \"First Method: \${NAME\[\*\]}\" echo \"Second Method: \${NAME\[@\]}\" The above example will generate the following result − \$./test.sh First Method: Zara Qadir MahnazAyan Daisy Second Method: Zara Qadir MahnazAyan Daisy **Example** \#!/bin/bash list=(File1 File2 File3 File4) for i in \${list\[@\]}; do echo\$i if \[ ! --f \$i \]; then echo Warning, \$i not found! fi done End....

Use Quizgecko on...
Browser
Browser