Friday, May 27, 2011

Chapter 10. Introduction to Shell Programming

Chapter Syllabus

10.1 Anatomy of a Shell Program

10.2 Using Variables

10.3 Command Line Arguments

10.4 Interactive Shell Programs

10.5 Exit Codes

10.6 The test Command

10.7 Branching

Shell programs or shell scripts are files containing HP-UX commands, comments, and control structures. These are like batch processes where commands are interpreted and executed by the shell line-by-line. Any command that can be executed at the shell prompt can be included in a shell program. Comments begin with a pound character (#) and are not executed by the shell. The POSIX shell allows use of control structures that can be utilized for branching and looping within the shell program. These control structures use test conditions for conditional branching and looping.

The shell provides very powerful features for writing shell programs. Many of the shell programs are used at startup and shutdown time and will be discussed in Chapter 13. These programs are shipped with HP-UX and provide control over many critical tasks related to system administration.

Shell programs are also used by system administrators to automate routine jobs. Files containing the shell commands are executed at specified times using the HP-UX cron facility. Mostly shell programs help in controlling the size of log files, cleaning temporary files, and reporting errors to the system administrator through email.

In this chapter, you will start with simple programs and analyze the parts of a typical shell program. Then you will learn how variables can be used to pass information to a shell program. Command line parameters can be passed to a program and utilized within it. The command line parameters may be useful for passing data or control information that is used during execution. Many times you may need to interact with your shell programs during the execution. You may also need to enter some values at run time. Interactive programs are very helpful for such applications, and you will learn how to read user input during their execution. When a program finishes execution, it returns a result code to the shell that is used to determine if the program terminated successfully. You will learn the use of exit codes, which are used to report any errors that occurred during the execution.

Variables are used to store values temporarily within the programs. In Section 10.2, you will learn how to utilize these variables inside shell programs. Before you can use some control structures, you need to test a condition. The result of this test allows you to make a decision. In the last part of the chapter, you will see how to use the test command and make decisions depending on its result.

This chapter includes the basic features of shell programming. The terms shell program and shell script are used interchangeably in this and the next chapter. In the next chapter, you will find some more-complicated shell programs containing loop structures.

10.1 Anatomy of a Shell Program

Let us go directly to our first program and analyze it. I have used the file name script-00 for this program. Contents of this file are shown below using the cat command.

$ cat script-00

#!/usr/bin/sh

# This is to show what a script looks like.

echo "Our first script"

echo "----------------"

echo # This inserts an empty line in output.

echo "We are currently in the following directory"

pwd

echo

echo "This directory contains the following files"

ls

$

Before looking into the program and explaining what each line does, let us see what happens if we execute it. We execute it from the current directory with the command line:

$ ./script-00

Our first script

----------------

We are currently in the following directory

/home/boota

This directory contains the following files

PHCO_18132.depot myfile phco_18132.txt

PHCO_18132.text phco_18131.txt script-00

$

The program prints some messages on your terminal screen and then shows the current directory and lists files in this directory.

Let us have a closer look at it. Basically, any shell program has three parts.

1. the full path of the subshell that will be used to execute the program

2. some comment lines

3. commands and control structures

I will explain these one-by-one.

Which Subshell Will Execute It?

The current shell executes all programs unless otherwise specified. In case you need to execute a program in a specific shell (Bourne, C, or POSIX), you can specify it in your program. In that case, a subshell is created as soon as a program starts execution. The first program line shows which HP-UX shell will be used to execute commands found in the program. This line always starts with the "#!" character combination and shows the full path of the executable program that will be used as shell. All HP-UX extrinsic commands have the same syntax no matter which shell is used to execute them. The difference is in the execution of intrinsic commands. For example, the method of setting a shell variable in the C shell is different from the one used in the POSIX shell. So you need to execute

your program in the proper shell. Depending on the information provided, your current shell will spawn the appropriate subshell to execute the program. As an example, you can't use the setenv command in a program that is expected to be run in a POSIX or Bourne shell because this command is specific to the C shell only.

In the example used here, the subshell that will be used to execute the program is /usr/bin/sh, which is the POSIX shell. You can use other shells, such as C, by changing this to /usr/bin/csh. It is a good habit to provide the shell name in the program so that if somebody else is using it in a different shell, the correct subshell is created and the program runs without any error.

Comments in a Shell Program

The second line in our example program contains a comment. A comment is that part of a program that is not executed. It is used for providing reference information about the program.

All comments start with a pound sign (#) except for the special combination used in the first line for specifying the subshell. A comment can be placed anywhere in the file. If a line starts with the "#" sign, all of the line is treated as a comment. If the "#" sign is placed somewhere else in a line, anything after that sign is considered a comment. In the example program script-00, comments are used in the second and fifth lines. The second line starts with the "#" sign, so all of the line is a comment, and nothing in this line is executed. The fifth line contains a command echo and after that a comment string. The command is executed but the comment is ignored.

Commands and Control Structures

This is the most important part of the program, where you put actual commands that are executed. The commands may be simple ones that the shell executes one-by-one, in the order they are placed in the program file. In the example program, we have used the commands pwd, echo, and ls. All of these commands

are executed in order and their result is displayed on your terminal screen as you have already seen. The echo command without any argument just prints a blank line.

The control structures are used for branching and looping. The decision of branching or looping is made depending on the result of a test performed on some variables or constants. We will discuss branching at the end of this chapter and looping in the next chapter.

Steps for Creating a Shell Program

A shell program is created in two basic steps. In the first step, a file is created that contains commands and control structures. This file is saved on the disk. Usually this file is not executable. In the second step, you need to modify file permissions to make it executable. If you are not sharing the program with others, you can use the chmod u+x command to make it executable. If you are sharing your program with other users, you need to set the appropriate permissions for this purpose.

You can also execute a shell program without the execute bit set if you use the program name as an argument to sh as shown below.

$ sh script-00

After setting appropriate execute permissions, you can execute a program. Care must be taken while naming shell programs such that the names do not match with any existing HP-UX commands.

If the current directory is not included in the PATH variable, you will not be able to execute the program by simply typing its name on the command line. For that purpose you need to specify the full path of the file. You can give the full path on the command line in either the absolute or relative form. The better way is the relative form, where you use "./" (dot slash) to refer to the current directory.

Note

Many times new script writers wonder why the script is not being executed, even though they have placed the correct commands and have the execution bit set. The reason is the directory in which they are placing the program is not included

in the PATH variable, and they are not specifying the path to the file explicitly. Sometimes it may happen that your current directory is included in the PATH variable at the end. When you execute your program without specifying the full path to the file, you get unexpected results. This is the case when you use a file name for a program that already exists on your system. What happens is the shell starts searching the file name from the first directory specified in your PATH variable. It gets the other file before it reaches the current directory and executes it. So it is always recommended to use "./" when you are testing your program for the first time to make sure that the shell is indeed executing the correct file.

Debugging Shell Programs

Debugging shell programs is a tricky business. There are many simple to complex procedures that can be applied for this purpose. Here is the simplest and basic method. You replace the first line of the program #!/usr/bin/sh with #!/usr/bin/sh -x. After that, when you execute the program, it displays each line on your terminal screen before executing it. The actual line present in the program is shown with a plus (+) sign in the start of the line. After that, its output is displayed. This method can be used to identify which program line is causing a problem. Below is the output of our example program script00 after this modification. Note that comments are not displayed.

$ ./script-00

+ echo Our first script

Our first script

+ echo ----------------

----------------

+ echo

+ echo We are currently in the following directory

We are currently in the following directory

+ pwd

/home/operator

+ echo

+ echo This directory contains the following files

This directory contains the following files

+ ls

PHCO_18132.depot myfile phco_18132.txt

PHCO_18132.text phco_18131.txt script-00

$

Study Break

Writing a Shell Program

If you are new to shell programming, this is the time to write your first shell program. Use the vi editor to create a new file named myscript. Use only one command (who) to list users currently logged into the system. Save the file and set its execution bit using the command chmod u+x myscript. Try to execute it and see if it is doing what you intend it to do.

10.2 Using Variables

Variables can be set and used in the same way you have used them on the command line. Any variable that is set during the execution of a shell program is not visible after the execution is finished. Shell programs can read environment variables and can also modify their values for the duration of the execution of the program. Variables are also a useful way of passing data to shell programs. Let us see another program named script-01 where we have set two variables TAB and FUR. These variables are then displayed using the echo command. The program is shown below.

$ cat script-01

#!/usr/bin/sh

echo "Use of Variables"

echo "----------------"

echo

TAB=table

FUR=furniture

echo "The $TAB is an example of $FUR"

$

When this program is executed, the results are:

$ ./script-01

Use of Variables

----------------

The table is an example of furniture

$

Note that these two variables are not available after the execution of the program is finished. If you try to display the values of any of these variables from the command line after executing the shell program, you will get the following message.

$ echo $TAB

sh: TAB: Parameter not set.

$

Now let us try to change the value of the TAB variable within the program from "table" to "chair" using the following program example (script-02).

$ cat script-02

#!/usr/bin/sh

echo "Use of Variables"

echo "----------------"

echo

TAB=table

FUR=furniture

echo "The $TAB is an example of $FUR"

TAB=chair

Echo "After change"

echo "The $TAB is an example of $FUR"

$

When this program is executed, the results are as follows. Note that the line used for printing the text is the same; only the variable value is changed.

$ ./script-01

Use of Variables

----------------

The table is an example of furniture

After change

The chair is an example of furniture

$

Passing Data Through Environment Variables

Shell programs can access environment variables. The example below is script-03, which prints the values of the PATH and TERM environment variables.

$ cat script-03

#!/usr/bin/sh

echo "The TERM variable is"

echo $TERM

echo "The current PATH setting is"

echo $PATH

$

The result after execution is:

$ ./script-03

The TERM variable is

ansi

The current PATH setting is

/baan/bse/bin:/usr/bin:/usr/ccs/bin:/usr/contrib/bin:/opt/

nettladm/bin:/opt/fc/bin:/opt/fcms/bin:/opt/upgrade/bin:/

opt/pd/bin:/usr/contrib/bin/X11:/usr/bin/X11:/opt/hparray/

bin:/opt/perf/bin:/opt/ignite/bin:/usr/sbin:/sbin:.

$

We can pass data to a program by using environment variables. As you already know, we can change the value of an environment variable in a program, but that change gets lost as soon as the program terminates. In script-04, we get an environment variable COLOR having value red and then change it to green. After execution of the program, when we check the value of the COLOR variable, it is still red. Let us first see the contents of script-04 and then execute it.

$ cat script-04

#!/usr/bin/sh

echo "The current COLOR variable is"

echo $COLOR

COLOR=green

echo "The new COLOR variable is"

echo $COLOR

$

Before executing this program, you need to set and export the COLOR variable. You can verify the exported value of the variable by using the echo command. After you execute the program, it changes the value and prints the new value green. When the program finishes, you use the echo command again to check the variable value, and you find out that it is the same as it was before executing the program.

$ COLOR=red

$ export COLOR

$ echo $COLOR

red

$ ./script-04

The current COLOR variable is

red

The new COLOR variable is

green

$

$echo $COLOR

red

$

10.3 Command Line Arguments

You can pass information to a shell program using command line arguments, the same as any other HP-UX command. These command line arguments can be used within the shell program. They are stored in variables, accessible within the program.

Using Command Line Arguments, or Positional Parameters

The command line arguments are stored in variables that show the position of the argument in the command line. That is why these are also called positional parameters. The variables that store command line arguments have names from $0 to $9. Beginning with the tenth command line argument, the argument number is enclosed in braces. The variable names are shown in Table 10-1.

Table 10-1. Variables for Storing Command Line Arguments

Variable Name

Description

$0

Shows value of the command itself (program name)

$1

First command line argument

$2

Second command line argument

.

.

.

.

.

.

$9

Ninth command line argument

${10}

Tenth command line argument

$#

Total number of command line arguments

$*

A space-separated list of command line arguments

Let's see script-05, which shows how many command line arguments are provided, a list of all arguments, and the value of the first argument. This program is now shown using the cat command.

$ cat script-05

#!/usr/bin/sh

echo "Total number of command line arguments is: $#"

echo "These arguments are: $*"

echo "The first argument is: $1"

$

When you execute the program with three arguments red, green, and blue, the result is as shown below.

$ ./script-05 red green blue

Total number of command line arguments is: 3

These arguments are: red green blue

The first argument is: red

$

The shift Command

The shift command is used to move the command line arguments one position left. The first argument is lost when you use the shift command. Shifting command line arguments is useful when you perform a similar action to all arguments, one-by-one, without changing the variable name. The shift command throws away the left-most variable (argument number 1) and reassigns values to the remaining variables. The value in $2 moves to $1, the value in $3 moves to $2, and so on. Let's modify script-05 into script-06 as shown below using the cat command.

$ cat script-06

#!/usr/bin/sh

echo "Total number of command line arguments is: $#"

echo "These arguments are: $*"

echo "The first argument is: $1"

shift

echo "New first argument after shift: $1"

shift

echo "First argument after another shift: $1"

$

Now let's execute script-06 with the same three arguments we used with script-05. You can see from the next result that after every shift, a new value is assigned to $1. This value is the variable that is just on the right side of $1 (i.e., $2).

$ ./script-06 red green blue

Total number of command line arguments is: 3

These arguments are: red green blue

The first argument is: red

New first argument after shift: green

First argument after another shift: blue

$

During the first shift operation, $1 value is lost forever and can't be recovered by the program. The shift command can also do multiple shift operations in one

step. For this you need to supply an argument to the shift command. For example, shift 2 will shift two arguments in one step, such that the old values of $1 and $2 will be lost, the value of $3 will be assigned to $1, the value of $4 will be assigned to $2, and so on.

Study Break

Use of Variables in Shell Programs

Variables play an important role in shell programs. To have some practice with the shell variables, modify script-06 so that before using the shift command, you store the value contained in $1 in another variable. Use the shift 2 command in the program and then try to print the $1 variable. Print the old value of the $1 variable using the echo command.

10.4 Interactive Shell Programs

Interactive shell programs can read user input at run time with the help of the read command. Most of the time you will use the echo command to display a message before the read command is executed. This message informs the user of what the program is expecting. These programs are used in situations where a program first checks some system parameter and then requires user input to perform an operation on it. As an example, if you want to talk to another user on the system, you may first want to see who is logged into the system. After getting a list of users, you may initiate conversation with a particular user using the talk command.

The read Command

The read command takes one line of input from the user and assigns it to a variable. The variable name is provided as an argument to the read command.

After entering some text, the user presses the key. Below is script-07, which lists all users currently logged into the system and then waits for you to enter a user name. After getting the user name, it initiates conversation with that user using the talk command.

$ cat script-07

#!/usr/bin/sh

echo "Currently logged in users are:"

who

echo

echo

echo "Enter the name of the user to whom you want to talk"

read NAME

echo "initiating talk with $NAME"

talk $NAME

$

After you select a user, the program rings the other party and displays a message asking the other user to respond to your talk request. If that user accepts your request, a talk window appears. Before the talk window appears, the program executes as shown below. Here you initiate a talk session with a user linda.

$ ./script-07

Currently logged in users are:

boota pts/t0 Oct 18 17:53

linda pts/0 Oct 18 22:13

Enter the name of the user to whom you want to talk

linda

The echo Command

You have already used the echo command to display text on your screen. This command uses escape characters that can be used to format the displayed text to enhance its readability. The escape characters used with the echo command are listed in Table 10-2.

Table 10-2. Escape Characters Used with the echo Command

Character

Effect

\a

Alert character (beep)

Table 10-2. Escape Characters Used with the echo Command

Character Effect

\b

Backspace

\c

Suppress new line at the end of displayed text

\f

Form feed

\n

Insert a new line character

\r

Carriage return

\t

Insert a tab character

\\

Backslash

\nnn

Character having ASCII value nnn in the octal format. The first n is 0.

In the example of script-07, the cursor goes to the next line after the message, "Enter the name of the user to whom you want to talk". If you want the cursor to stay in the same line until you enter the user name, you need to suppress the new line character by using \c in the echo command as follows.

echo "Enter user name to whom you want to talk \c"

You can also use \a to add a beep to your program as soon as this command is executed.

10.5 Exit Codes

When a program terminates its execution, it returns a result code to the shell that shows the termination or exit status of the program. In the case of termination after successful execution, this code is zero. If the program terminates abnormally, the exit code is not equal to zero. The exit code of the last executed program can be checked by displaying the value of a special variable $?. See the following examples to get an idea of how the exit code works.

$ ls

PHCO_18132.depot phco_18132.txt script-02

PHCO_18132.text scr script-03

phco_18131.txt script-01 script-05

$ echo $?

0

$

$ mv

Usage: mv [-f] [-i] [-e warn|force|ignore] f1 f2

mv [-f] [-i] [-e warn|force|ignore] f1 ... fn d1

mv [-f] [-i] [-e warn|force|ignore] d1 d2

$ echo $?

1

$

The first command is the ls command, which executed successfully. After that, you used the echo $? command, and it showed you an exit code zero. The second command was mv. You did not provide any argument to this command, which is a must, so the command terminated abnormally and returned a value of 1.

You can use exit codes in your program to check the execution status of any commands used within the program. If a command used in the program did not execute successfully, you can make corrective measures.

You can also terminate your shell program at any point by using the exit command. The exit command can be supplied with an argument that will show the exit status of your program and can be used for debugging purposes. As an example, if you are writing a program and it needs at least one command line argument, you can terminate its execution if no argument is supplied.

10.6 The test Command

Branching decisions are made depending on the result of a test command. The test command can perform tests on numeric and string data as well as on files. The test command returns a true or false value. The true value is always zero, while false is a number other than zero. Usually this number is one. You can check the result code of the test command to make a branching decision. The test command can be used in explicit or implicit modes. In the explicit mode, the test command is used as follows.

$ test "ABC" = "abc"

In the implicit mode, the word "test" is not there; square brackets are used instead.

$ [ "ABC" = "abc" ]

The command does not print anything on the terminal screen. The result code can be checked using the $? variable as explained earlier in the chapter.

Testing Numeric Values

Tests can be performed to compare two or more integers. The relations that can be used with numeric data are shown in Table 10-3.

Table 10-3. Numeric Tests

Relation

Description

-eq

Equality check

-ne

Not equal

-lt

Less than

-gt

Greater than

-le

Less than or equal to

-ge

Greater than or equal to

Numeric testing will be used in shell programs later in this chapter.

Testing String Values

The string values can be checked for equality and nonequality. Other than that, a single string can be tested if it has a zero length or not. The string operations are shown in Table 10-4.

Table 10-4. String Tests

Operation

Description

string1 = string2

True if string1 and string2 are equal

string1 != string2

True if string1 is not equal to string2

-z string

True if string length is zero

-n string

True if string length is nonzero

string

True if string length is nonzero

Testing Files

Testing on files can be performed in many ways. Some of these are shown in Table 10-5. A list of other supported file tests can be found using the man sh-posix command.

Table 10-5. File Tests

Operation

Description

-d file

True if the file is a directory

-f file

True if the file exists and is a normal file (not a directory)

-s file

True if the file is more than zero bytes in length

-r file

True if the file is readable

-w file

True if the file is writable

-e file

True if the file exists

-L file

True if the file is a symbolic link

file1 -nt file2

True if file1 is newer than file2

file1 -ot file2

True if file1 is older than file2

-x file

True if the file is executable

For example, if file file1 exists, and you use the following command to check its existence, you will get an exit code of zero (true).

$ [ -f file1 ]

$

$ echo $?

0

$

Testing with Logical Operators

Logical operations can be performed on two expressions with one of the logical operators shown in Table 10-6.

Table 10-6. Logical Operators

Operation

Description

expr1 -o expr2

Logical OR, true if either expr1 or expr2 is true

Table 10-6. Logical Operators

Operation Description

expr1 -a expr2

Logical AND, true if both expr1 and expr2 are true

! expr

Logical NOT, true if expr is false

The following code segment tests files represented by the first two command line arguments and prints a message if both files exist.

#!/usr/bin/sh

if [ -f $1 -a -f $2 ]

then

echo "Test successful"

fi

10.7 Branching

Two types of branching are used in shell programming. One of these is represented by the if structure and the other one by the case structure. In this section, you will learn how to use both of these branches. You will also find some useful examples of shell programs.

The if-then-fi Structure

The if-then-fi structure is used to check a condition with the help of a test command. If the test returns a true value, then an action is performed. If the test returns a false value (not true), the action part of the program is not executed. The general syntax of this structure is as follows.

if expr

then

action

fi

where expr is a test performed on some variables or constants. The action is a set of one or more commands that are executed if the test returned a true value. This is shown in Figure 10-1 using a flow diagram.

Figure 10-1. The if-then-fi structure.

Previously you have seen how to check the number of arguments on the command line. You can write a shell program to check the number of arguments and print an error message if there is no argument on the command line. The program script-08 does the same thing and is listed here using the cat command.

$ cat script-08

#!/usr/bin/sh

if [ "$#" -lt 1 ]

then

echo "Error: No arguments provided on command line"

exit 3

fi

echo "Program terminated normally"

$

When you execute this program without any command line argument, you will see the following message on your screen.

Error: No arguments provided on command line

If you check the return code using the echo $? command, a value of 3 will appear. On the other hand, if you provide at least one argument on the command line, the return code will be zero and the message on your screen will be:

Program terminated normally

This is a useful way of checking the number of command line arguments if your program expects a fixed number of arguments. For example, the cp command requires two command line arguments showing the source and destination paths of the file being copied. If you don't provide two arguments, the command prints an error message.

The if-then-else-fi Structure

This structure is used when you want to perform one of two actions, depending on the result of a test. The general syntax of the structure is:

if expr

then

action1

else

action2

fi

If the result of expr is true, action1 is performed. In the other case, action2 is performed. Each of action1 and action2 may be a set of one or more commands. The flow chart of this structure is shown in Figure 10-2.

Figure 10-2. The if-then-else-fi structure.

You can modify script-08 so that it accepts two file names as argument and copies the first file to the second file. If there are not exactly two arguments, it tells you that you did not provide two arguments. It then displays all of the arguments it received from the command line. The modified form is script-09.

#!/usr/bin/sh

if [ "$#" -eq 2 ]

then

cp $1 $2

else

echo "You did not provide two arguments."

echo "The arguments provided are $*"

fi

echo "Program terminated"

This program works fine, but it does not incorporate any facility for dealing with a problem. The next program, script-10, is a more sophisticated shell program that performs a number of checks before copying one file to another. It first checks the number of arguments, and if you have not provided two arguments, it terminates at that point. Then it checks if the source and destination files are the

same. If they are, it terminates at this point. The next check is to verify that the source file exists and that it is not a special file. After that, it checks if the source file exists and is readable. If both of the conditions are true, it checks the destination file. If the destination file already exists, it asks if you want to overwrite it. If you say "yes," it copies the source file to the destination; otherwise it terminates. If the destination file does not exist, it copies the source to the destination without interacting with you.

#!/usr/bin/sh

if [ "$#" -ne 2 ]

then

echo "You have not provided exactly two arguments."

exit 1

fi

if [ "$1" = "$2" ]

then

echo "Source and destination names are the same."

exit 1

fi

if [ ! -f "$1" ]

then

echo "File $1 does not exist or not a regular file."

exit 2

fi

if [ ! -r "$1" ]

then

echo "File $1 is not readable."

exit 3

fi

if [ -f $2 ]

then

echo "File $2 already exists. Do you want"

echo "to overwrite (yes/no): \c"

read ANSWER

if [ "$ANSWER" = "yes" ]

then

cp $1 $2

echo "File copied"

exit 0

else

echo "File not copied"

exit 4

fi

fi

cp $1 $2

echo "File copied"

The exit status is different at every point so that you may come to know at what stage the program terminated by checking the exit code. You can use this

program in place of the standard cp command as it is safer and does not overwrite existing files without notification.

The case Structure

The case structure is used where you want to branch to multiple program segments depending on the value of a variable. The general syntax of the case structure is:

case var in

pattern1)

commands

;;

pattern2)

commands

;;

patternn)

commands

;;

*)

commands

;;

esac

The value of var is checked. If this is equal to pattern1, the commands in the first block are executed. The first block ends at the ;; pattern. If the value of var matches pattern2, the commands in the second block are executed. If var matches none of the pattern values, the commands in the last block after "*)" are executed. This last part is optional and can be omitted. The case statement is shown in the flow diagram of Figure 10-3.

Figure 10-3. The case structure.

Program script-11 is used as an example here. It provides you with a few choices. If you select one of these, appropriate action is taken.

#!/usr/bin/sh

echo "Press w to list users"

echo "Press d to see date and time"

echo "Press p to see current directory"

echo

echo "Enter your choice: \c"

read VAR

case $VAR in

w|W) who

;;

d|D) date

;;

p|P) pwd

;;

*) echo "You have not pressed a valid key"

esac

echo "The case structure finished"

For example, if you press "w" or "W", the list of users currently logged into the system is displayed. Note that the "|" character is used for the logical OR operation in the case structure. If you make a choice that is not valid, the last part of the case structure is executed, which shows that you need to make a valid choice. Wildcard and range characters (*, ?, [ ]) can also be used in patterns to be matched.

Test Your Knowledge

1:

You create a shell program and save it into a file with name "more". Your current directory name is included in the PATH variable at the end. When you run this program by typing "more", nothing happens and the cursor just stops at the next line. What may be the problem?

A. You have written some commands in the program that the shell does not understand.

B. The shell program file is not executable.

C. You have used a program name that matches a standard HP-UX command.

D. There is a problem with your terminal and you need to reset it.

2:

What is true about variables used in shell programs?

A. Variables starting with letters can be used in programs.

B. Values of variables can be changed in the programs.

C. The shell can read and modify environment variables for its own use.

D. All of the above.

3:

You use the echo $? command. The result is 2. What do you conclude from this?

A. The echo command printed the number of characters in its first argument.

B. The last command terminated abnormally.

C. The "?" symbol has an ASCII value equal to 2.

D. None of the above.

4:

You used shift 3 in your shell program. What will be its effect?

A. It will shift the first three command line arguments to the left.

B. It will shift the last three command line arguments to the left.

C. It will shift all command line arguments by three places toward the left.

D. It will shift all command line arguments by three places toward the right.

5:

What does the echo "\a" command do?

A. It prints the character a.

B. It prints the character \a.

C. It prints a hexadecimal character "a" that represents decimal 10.

D. It gives a beep sound.

6:

What is wrong with the command [ "ABC" -eq "ABC" ]?

A. You are comparing strings with a numeric operator.

B. The same string is used on both sides of the operator.

C. The quotation marks are not needed here.

D. Parentheses should be used instead of square brackets.

7:

A shell script with the name myscript does not have the execution bit set. How can you execute it?

A. exec myscript

B. sh myscript

C. run myscript

D. No shell script can be executed until its execution bit is set.

8:

How can you list all command line arguments?

A. using $*

B. using $#

C. using the shift command

D. using the list command

9:

The true return value of the test command is:

A. 1

B. 0

C. any positive number

D. any number not equal to zero

10:

You have a shell script as shown here. What will be the result when it is executed?

#!/usr/bin/sh

ABC=aac

case $ABC in

a) echo "First"

;;

[aa]c) echo "Second"

;;

a*) echo "Third"

;;

*) echo "Last"

;;

esac

A. First

B. Second

C. Third

D. Last

10 comments:

  1. That is the excellent one post here. Thank you and all the best.
    digital marketing services in delhi

    ReplyDelete
  2. Tevida important that you know the ingredients in order to know if there is any content that is a threat to your health. Allergic reactions will also be prevented if you know the content, since you can avoid buying supplements that contain ingredients that can cause your allergies.Do some research on the content of
    https://www.supplementsforfitness.com/tevida/

    ReplyDelete
  3. Quit 9 to 5 Academy program is the proficient program to guide everyone who wants to know the ways to squash it will affiliate marketing by making use of paid traffic. In Quit 9 to 5 Academy Reviews by Mark Ling, trainees will get to know about in what way to produce vital earnings by promoting digital items online with the main aim of changing their full-time wage. There only some online courses that can truly offer tremendous value to beginners as well as advanced media buyers in the same way.

    ReplyDelete
  4. Health Discreet

    is a place to find honest reviews on health supplements from

    best of the brands. Here, customers are going to get complete

    information on almost every top rated product from different

    countries. The authenticity of our website is clearly visible

    through popular health blogs with the name mentioned in it.We

    provide our best support to the visitors seeking details of

    the supplements and comparisons between them.

    ReplyDelete
  5. commonly addicted and they may be around for a rattling abundant example. This is why the cardiologist complex so scheming at the hindering drug so as to neutralize and eventually happening travel of disease. The cardiologist has to convey a fleshly touch as intimately as an interview of the enduring so as to open their procedure and also forebode if there may be issues with the suspicion. There is also a requisite to visit few organs eudaemonia of the patient is continuous and improved. Characteristic investigating The important ride that a specialist uses is the echocardiogram shortened as ECG. This allows the specialist to mate whether the organs health of the tolerant is satisfactory or not. It is the portrayal of the specialist to construe the results as seen. He should also ingeminate else results conducted on the excretion and gore of the longanimous. The emphasis http://givinghealthylife.com/

    ReplyDelete
  6. https://apkchip.com League of Legends - the courageous filled with terminologies, ethical from smurfing and ganking bot; it sometimes is uphill to realise what these phrases normal. Suppose you are playacting a scheme of Legends for a unsound indication then you moldiness be sensible of the quantity "elo boosting". But, what's elo boosting or why is everybody talking nigh this? Presume you love never heard near the statue elo boosting, then you are not unprotected to "concealed" of LoL boosting. Let us realize statesman most how it works, we eff put unitedly the direct that anybody can see real easily!

    ReplyDelete
  7. commenting about the technical facts like graphics calibre, lags, etc. of the spirited. At times, you give also descend across reviewers who fund healthy or bad ratings for fun or for their own benefits. So it is always sensible to do your own researches and ask your play friends for suggestions. Do you request to termination your unfixed measure when the exclusive companionship you possess is your Robot sound? Did you cognise that Humanoid games are the most absorbing and fun filled nonsense to study your sound with? Go finished this article to experience solon active these games and their fun factors. Robot games are heterogeneous into numerous categories; informational, educational, propulsion games, puzzles, sports, racing, augmented experience games, location-based games and statesman. All these types are lendable for both swollen end and low-end Humanoid phones. There are low restriction games for those low-end models so that you can like them in your budget phones as substantially. This includes the lesser graphics knowledge games that does not necessitate overmuch
    https://seekapk.info

    ReplyDelete
  8. https://apkchip.com Most of the games protect you confirmed to them that patch activity you rightful block the indication locomotion by. There are galore reports that present how a player gets hooked to these that they end up fatality themselves or they get so hooked up in the sound that they jibe with many form of accidents.

    ReplyDelete
  9. The Probiotic supplement helps to balance good bacteria and in this regard, Zenith Labs Probiotic T-50 Review is creating buzz. How far is the supplement reliable and worth considering, you will come to know about it here.

    ReplyDelete


  10. aboutthemcat
    How Does RLZ Pills Win to Compound your Action?

    The very low aim of testosterone in men may reason a open limit of health problems which countenance sexed health stock also; expansive pathology, deficiency of motive, and strengthen tiredness. The first intellection transform to renew the testosterone levels in guys is to advise all the basic supplements in the body. Furthermore, this is the powerful phallic improvement and facilitative. RLZ Pills are the motley of the enthusiastic ingredients which are clinically proved and proven that offers you most extremum implementation even. The Manly Performance instruction attempts to furnish you with the higher continuance and dimension that enable you to move, and slaying flows into the body, safekeeping you from deed an inopportune flow and bask incompatible your copulation.

    CLICK for more info>>>http://aboutthemcat.org/rlz-male-enhancement/

    ReplyDelete