Computer Programming

happy666
HW1_ShellProgramming1.pdf

CSE 4600 Homework 1 Shell Programming

ShellProgramming.html[8/26/20, 1:53:44 PM]

Homework 1 Shell Programming Due: Sept 4th, 2020 @11:55 PM

Highlights

1. Different Shells 2. Writing and executing Shell script example 3. Variables 4. Conditionals 5. Loops 6. Arithmetic Evaluation 7. Homework Exercise

1. Different Shells

There are several different shells, they offer their own advantages and disadvantages. For instance, some allow for auto completion using the tab key; others don't.

A few common shells are the following:

Bourne shell (sh) Bourne again shell (bash) C-shell (csh) C shell with file name completion and command line editing (tcsh) Korn shell (ksh)

To see what shells exist on your current Unix system, try the following command:

$ cat /etc/shells

To see what shell you are using, try the following command:

$ echo $0

From the command line, you can type various commands which have the same responses in each of these shells. For instance chmod, ls, cd, and touch.

2. Writing and executing Shell script example

If you need to type the same commands over and over again, it is good to create a shell script.

For example, you could create a basic shell script by:

1. Typing the following lines into a file called team.sh:

#!/bin/bash

CSE 4600 Homework 1 Shell Programming

ShellProgramming.html[8/26/20, 1:53:44 PM]

# team.sh ls -l mkdir team cd team touch alice monica george

2. Making the file executable:

chmod +x team.sh

3. Executing the file at the command line:

$ sh team.sh or $ ./team.sh

Executing team.sh will do the following: first do a long listing of the current directory, then make a directory called team, and create files: alice, monica, and george under the team directory.

Any line preceded with # is a comment (or anything after the # is ignored):

#!/bin/bash #list the files in the current directory ls -l

#make a directory called team mkdir team

#change into the team directory and create three files. cd team touch alice monica george

The special notation used on the first line of the shell script (beginning with a number sign (#), then an exclamation point (!), followed by the full path name of the shell on the computer's file system) states that we will interpret the commands with the bash shell on our Linux system.

There is a major split between Bourne-compatible shells (such as sh and bash) and csh-compatible shells (such as csh and tcsh). These differences show up in such things as conditional statements and loops.

For the remainder of this lab, we will be focusing on bash shell scripts. For more details about bash, please click Bash Guide for Beginners, and Bash Shell Programming.

3. Variables

You can use variables as in any programming languages. There are no data types. A variable in bash can contain a number, a character, a string of characters. To declare a variable and assign with a value, use VARIABLE_NAME=VALUE expression (with no spaces in between). For instance,

#!/bin/bash city="San Bernardino" course="CSE4600 OS" capacity=30

In the above example, we have declared a few variables with different data types. But Bash does not have a type system, it can only save string values. Hence internally, Bash saves them as a string.

CSE 4600 Homework 1 Shell Programming

ShellProgramming.html[8/26/20, 1:53:44 PM]

There is a difference in shell scripts between the name of a variable and its value:

If myvar is the name of a variable, then $myvar is a reference to its value. The only time a variable is "naked" (without the $) is when it is declared, assigned, or exported.

To print a value, we use echo command. It is a binary file located inside /bin. It takes arbitrary arguments which could be a string or a variable.

city="San Bernardino" echo $city

We can read user input in the terminal using read command. When the user input the text and hit enter, that entire text will be saved in a variable.

#!/bin/bash # readeg.sh echo "Enter a name:" read name echo "Your name is:" $name

Execute the above script, we may get,

Enter a name: John Your name is: John

An example of assigning and using variables is the following code:

#!/bin/bash #file: variables.sh

var1="My string with spaces" echo "var1 is: " $var1 echo

echo "Enter a number: " read var2 echo "var2 is: " $var2 echo

A sample run would yield the following results:

$ ./variables.sh var1 is: My string with spaces Enter a number: 30 var2 is: 30

4. Conditionals

At times you need to specify different courses of action to be taken in a shell script, depending on the success or failure of a command. The if construction allows you to specify such conditions.

The general syntax of the if command is:

CSE 4600 Homework 1 Shell Programming

ShellProgramming.html[8/26/20, 1:53:44 PM]

if TEST-COMMANDS then CONSEQUENT-COMMANDS else ALTERNATE-CONSEQUENT-COMMANDS fi

The TEST-COMMAND takes one of the following syntax forms:

test EXPRESSION [ EXPRESSION ] [[ EXPRESSION ]]

The TEST-COMMAND list is executed, and if its return status is zero, the CONSEQUENT-COMMANDS list is executed, otherwise the ALTERNATE-CONSEQUENT-COMMANDS list is executed. The return status is the exit status of the last command executed, or zero if no condition tested true.

The TEST-COMMAND often involves numerical or string comparison tests, but it can also be any command that returns a status of zero when it succeeds and some other status when it fails. Unary expressions are often used to examine the status of a file. Please refer to File test operators for more file test operators.

You can use the exit status of commands in conditions. Be careful that you are checking the status variable directly after executing the command.

#!/bin/bash #file cond.sh

echo -n "Enter a number: " read VAR

if (( $VAR > 0 )) then echo "$VAR is greater than 0." else echo "$VAR is equal or less than 0." fi echo

FILE=/etc/resolv1.conf if [ -f "$FILE" ] then echo "$FILE exists" else echo "$FILE does not exist" fi echo

read WORD FILE=main.cpp grep $WORD $FILE

if [ $? == 0 ] then echo "$WORD is in $FILE" else echo "$WORD is not in $FILE" fi echo

5. Loops

The for loop

The for loop is the first of the three shell looping constructs. This loop allows for specification of a list of values. A list

CSE 4600 Homework 1 Shell Programming

ShellProgramming.html[8/26/20, 1:53:44 PM]

of commands is executed for each value in the list. The syntax for this loop is:

for NAME in [ LIST ] do COMMANDS done

The return status is the exit status of the last command that executes. If no commands are executed because LIST does not expand to any items, the return status is zero.

NAME can be any variable name, although i is used very often. LIST can be any list of words, strings or numbers, which can be literal or generated by any command. The COMMANDS to execute can also be any operating system commands, script, program or shell statement. The first time through the loop, NAME is set to the first item in LIST. The second time, its value is set to the second item in the list, and so on. The loop terminates when NAME has taken on each of the values from LIST and no items are left in LIST.

The while loop

The while construct allows for repetitive execution of a list of commands, as long as the command controlling the while loop executes successfully (exit status of zero). The syntax is:

while CONTROL-COMMAND do CONSEQUENT-COMMANDS done

CONTROL-COMMAND can be any command(s) that can exit with a success or failure status. The CONSEQUENT- COMMANDS can be any program, script or shell construct.

As soon as the CONTROL-COMMAND fails, the loop exits. In a script, the command following the done statement is executed.

The return status is the exit status of the last CONSEQUENT-COMMANDS command, or zero if none was executed.

The following is an example of these two looping structures:

#!/bin/bash #file: loops.sh FILE='./main.cpp'

#A while loop with user input echo "Enter a letter or x to quit " read var1

while [ $var1 != "x" ] do echo "Enter a letter or x to quit " read var1 done

#A for loop echoing the contents of file if [ ! -f $FILE ] then echo "$FILE is not found." exit 1 else for var2 in $(cat $FILE) do echo $var2 done fi

CSE 4600 Homework 1 Shell Programming

ShellProgramming.html[8/26/20, 1:53:44 PM]

6. Arithmetic Evaluation

We can perform arithmetic operations in Bash even though Bash does not support number data type.

We have two kinds of operators:

arithmetic relational

Using $((expression)) syntax, we can also perform arithmetic operations.

The following table summarizes some of these operators:

Arithmetic Operators * multiplication / division + addition - subtraction % modulo-results in the remainder of a division ++ increment operator -- decrement operator Relational Operators > greater-than < less-than >= greater-than-or-equal-to <= less-than-or-equal-to = equal in expr == equal in let != not-equal & logical AND | logical OR ! logical NOT

An example of several of these are in the following sample code:

#!/bin/bash # file: arithmetic.sh

num1=3 num2=10

echo $num1 echo $num2

res=$((num1+num2)) echo "num1 + num2 = $res"

res2=$((num1*5)) echo "num1 * 5 = $res2"

CSE 4600 Homework 1 Shell Programming

ShellProgramming.html[8/26/20, 1:53:44 PM]

res2=$((num1%5)) echo "num1 % 5 = $res2"

#Decrement or increment ((res2++)) #increment operator # ((res2--)) #decrement operator

echo $res2

#Logical assignment mybool=$((!($res2==$res)))

# mybool=$(($res2 > $res)) echo $mybool

A sample run of the program would look like this:

$ ./arithmetic.sh 3 10 num1 + num2 = 13 num1 * 5 = 15 num1 % 5 = 3 4 1

7. Homework exercise

Your task is to create a bash shell script that is able to backup all the C++ program files in your current directory.

The algorithm is as follows:

Prompt the user to enter a backup directory name. If the backup directory does not exist in the current directory, then create the backup directory. For each .cpp file in the current directory,

If there have been changes to the file since the last backup or no copy exists in the backup directory, then copy the current .cpp file to the backup directory and print a message that the file has been backuped. Otherwise, no copy will be made, and print a message that the file is the latest.

Deliverables:

1. The code of bash shell script hw1.txt. The shell script file should be hw1.sh, but .sh files can not uploaded to Blackboard, please revise the extension as .txt and then upload it to Blackboard.

2. The script log file hw1log.txt showing the test cases outlined below

Test Cases captured in hw1log.txt :

1. Start by removing your backup directory (rm -r backup) 2. Ensure that there are some .cpp files in the current directory 3. Show the directory using ls -l 4. Run the backup script file hw1.sh several times as specified below:

Type "backup", to create a backup directory ls -l backup Run your backup script file hw1.sh ls -l backup Append to all the files and rerun your backup script file hw1.sh an good way to append is to type: echo "something" >> file.cpp Append to one file and rerun your backup script file hw1.sh

CSE 4600 Homework 1 Shell Programming

ShellProgramming.html[8/26/20, 1:53:44 PM]

Create a new .cpp file (using touch) and rerun your backup script file hw1.sh

Notes

Do not create a zip file Submit on Blackboard, before submitting, please change the extension name of hw1.sh as hw1.txt, .sh files can not be uploaded to Blackboard Be mindful the due date!

Copyright © 2020. All rights reserved.

  • Local Disk
    • CSE 4600 Homework 1 Shell Programming