UNIX Shell Scripting Basics

Understanding UNIX shell scripts
1. Command-line processing
The UNIX shell is a command-line interpreter that processes each command or combination of commands on a command line when you press Enter. This example shows only a single command on the command line. $ sort -r userlist You can combine multiple commands on the same command line by creating a composite command. This example shows a composite command comprising the ls and less commands. $ ls -l | less You can use a number of special characters in the command line. A semicolon (;), for example, allows you to place more than one command statement in the same command line. When you enter the code, the shell executes the preceding commands only when it reaches the semicolon. In this example, the shell executes the cp command statement and then the cat command statement. $ cp list list.bak; cat list.bak Special characters you can use to manipulate commands in the command line include y y y y y backslash (\) greater than (>) less than (<) pipe (|) ampersand (&)

backslash (\) The backslash (\) character prevents the shell from treating another character as a special character through a process called backslash escaping. This allows you to split a command statement across multiple lines. When you place the backslash at the end of a line and then press Enter, you can continue the statement on the next line. The backslash prevents the shell from treating the Enter keystroke ± or new line

character ± as a special character. This example shows a long echo statement carried across three lines. The code for this is $ echo Long pieces of text may not always fit onto a single \ > line of the command line interface, so it becomes \ > necessary to split them across multiple lines using \ > backslashes. greater than (>) The greater-than character (>) allows you to direct the standard output of a command to a file or a device such as a printer instead of to the terminal screen. This example will send the output of the ls command to a file called userdirs. The code for this is $ ls -l /usr/home > userdirs less than (<) The less-than character (<) allows you to send the contents of a file to a command as its standard input. This example sends input from a file called list to the sort command. The code for this is $ sort -d < list pipe (|) The pipe character (|) allows you to direct the output of one command to the input of another command. This example pipes the output from the cat command as input to the grep command for further processing. The code for this is $ cat EasyNomad | grep 'South America' ampersand (&) An ampersand (&) character at the end of a command statement allows you to run commands in the background.

This example specifies that the find command will run a long search process in the background. The code for this is $ find 'EasyNomad' & [1] 48748 $ EasyNomad If you want to use special characters in command-line text without the shell recognizing them as special characters, you have to enclose them in quotes or precede them with a backslash (\). This example shows an echo command in which the echo text contains an ampersand. There's a backslash in front of the ampersand, which prevents the shell from treating it as a special character. $ echo Tours \& Accommodation Tours & Accommodation $

Question
How do you think the shell processes the contents of a command line in order to execute it? Options: 1. 2. 3. 4. By analyzing commands first and then proceeding to options and arguments By dividing the command line into segments and processing each segment By processing the command line from beginning to end, one character at a time By processing the command line from beginning to end, one word at a time

Answer
When you execute a command line, the shell looks for spaces and special characters and splits the command line into segments wherever these characters occur. It then processes each segment in turn. The segments into which the shell divides a command line are called tokens. To execute a command line, the shell processes the first token and then each subsequent token in turn. To begin processing a token, the shell checks whether it's a keyword, an alias, or an ordinary word.

If the token is a keyword that opens a substructure such as a function, conditional statement, or bracketed group of commands, the shell processes the substructure before moving on to the next token. If a token is an alias, the shell replaces it with the command to which the alias is mapped. If a token is an ordinary word such as a command or a filename, the shell processes it directly. After comparing a token against the list of known keywords and aliases, the shell processes it using several stages of expansion and substitution. Expansion and substitution takes place in the following sequence: y y y y y y y brace expansion tilde expansion parameter substitution command substitution arithmetic substitution word splitting pathname substitution

brace expansion In brace expansion, the shell looks for braces ({}) ± also called curly brackets ± in the token. If braces are present, it expands their contents. For example, the token b{all,ook} expands into ball book. tilde expansion In tilde expansion, the shell looks for tildes (~) in the token. If a tilde is present, it replaces the tilde with the location of the current user's home directory. For example, depending on the system configuration, the token ~vincep/file2 might expand into /usr/home/vincep/file2. parameter substitution In parameter substitution, the shell checks whether the token is a variable name preceded by a dollar sign ($). If it is, the shell replaces the token with the current value of the corresponding variable. For example, if the value of the SHELL parameter is /bin/ksh, the token $SHELL is replaced with /bin/ksh. command substitution In command substitution, the shell checks whether the token is a command enclosed in brackets and preceded by a dollar sign ($). If it is, the shell processes the command and

the shell replaces the token $((72/9)) with 8. Once the shell has identified which command it needs to execute. the shell checks whether the token is an arithmetic expression enclosed in double brackets and preceded by a dollar sign.txt funding. it splits them into tokens for processing.txt flights. 2. the shell looks for wildcard characters in the token. word splitting In word splitting. For example.txt. processing its tokens in the same way. pathname substitution In pathname substitution. or double slashes (//). the shell examines those parts of the command line that have resulted from previous stages of expansion and substitution. the token f*. Question Which special character is used to run a command in the background? Options: 1. If it is. and pathnames. After performing expansion and substitution. denoted by a semicolon or a new line character. If any of these contain spaces or special characters. For example.replaces the token with the command's output. For example. It then moves on to the next command. & | . question marks (?). depending on the files in the current directory. the token $(type username) might be replaced with vincep. arithmetic substitution In arithmetic substitution. \ . it searches the current directory for filenames that match these wildcards and substitutes them for the token. it executes the command to produce output. the shell evaluates the expression and replaces the token with the result. 3.txt might expand into fares. built-in commands. 4. If it finds asterisks (*). Then it matches the command against its list of known functions. the shell processes subsequent tokens until it reaches the end of a command.

Commands on the right of the semi-colon are only interpreted once commands on the left have been interpreted and executed.2. Option 1 is correct. In this example of command substitution. . The contents of the hostname file are used as a search term by the grep command. the command cat /etc/hostname is processed before the grep command is executed. 4.com > hosts ls * | grep "easynomad" Answer The code $(cat /etc/hostname) is an example of command substitution. Option 1 is correct. The path ~/documents expands to the documents folder in the home directory of the current user.easynomad. Question Choose the code that contains an example of command substitution. 3.Answer The ampersand symbol (&) is used to run a command in the background. You can you can use this number to foreground the job again. The pipe (|) special character allows you to use the output of the command on the left of the pipe as input for the command on the right of the pipe.3). Option 4 is incorrect. so that its output can be substituted into the grep command. Option 2 is incorrect. The backslash (\) is used to prevent special characters from being interpreted in such a way that their literal values are used in stings. to run a job in the background. This is an example of tilde substitution. Jobs in the background are assigned a job id number. cat logfile | grep $(cat /etc/hostname) cd ~/documents echo server{1. The ampersand symbol (&) is used at the end of a command. The semi-colon (. 2. Also. Options: 1. you can continue your command on a new line by typing a backslash before pressing Enter.) is used to combine separate commands on the same line. Option 2 is incorrect. Option 3 is incorrect.

4.com. Teresa LOGAN. the ls command executes without errors ( so its exit state is zero. Daniel CARUSO. To make one command conditional on another. Question How do you think the shell knows whether a command has executed successfully? Options: 1. Option 4 is incorrect. you can use a first command to check whether a file exists and a second command to perform an operation on it if it exists. if it executes successfully. server2. Greg .easynomad. Command grouping You can join commands on a command line in such a way that the second command executes only if the first command has executed successfully.3).easynomad.com.com is expanded as: server1.com.2. The command after the && symbols executes only if the command before the && symbols produces a zero exit status ± in other words.easynomad. the ls command checks whether the userlist file exists. Maria GARZA. Because the command terminates Because the command's exit status is zero Because the command's standard error output is null Because the command's standard output contains no error messages Answer The shell knows that a command has executed successfully when the exit status of the command is zero. For example. The code ls * lists every file in the current directory. This is an example of brace expansion.Option 3 is incorrect. 3. Because it does exist. server3. In this example. This causes the sort command to execute. you join the commands using a double ampersand (&&).easynomad. 2. The code server{1. 2. This is an example of filename substitution. $ ls userlist && sort userlist userlist BAKER.

this means that the file already exists. Glen OSWALD. The shell treats any command block enclosed in braces as if it were a single command. the touch command doesn't execute.MANEROWSKI. Because the sort command is conditional. the ls command encounters an error ± so its exit state is non-zero. Debora $ If you delete the userlist file and run the command again. the ls command looks for a file called userlist. In this example. the second command executes only if the first command has a non-zero exit state. $ ls userlist && sort userlist ls: userlist: No such file or directory $ You use a double pipe (||) to make a command conditional on the unsuccessful execution of the previous command. the touch command creates it. In this example. $ ls userlist || touch userlist userlist $ You can group commands using braces ({}). Vince REILLY. Sarah NOVAK. This allows you to redirect input and output to and from a group of commands. Nicholas NOVIALLO. Molly STROTHER. Tanya WADE. . Sam PASCUCCI. In such a case. the braces group the sort and grep commands into a code block so that the shell sorts input and then extracts any lines containing the word Mexico. $ ls userlist || touch userlist ls: userlist: No such file or directory $ If the ls command executes successfully. the shell doesn't attempt to execute it. If it fails to find the file. In this case.

Option 1 is correct.easynomad.easynomad. $ {sort | grep 'Mexico'} < flights > mex_flights $ You can group commands using round brackets ± often called parentheses ± instead of braces.com.easynomad. 4.com > hostname cat hostname && echo easy1. cat hostname || echo easy1. you don't want to overwrite any existing file by that name. the code specifies the flights file as input and the mex_flights file as output.easynomad. it will get overwritten.$ {sort | grep 'Mexico'} You can redirect input and output to a command block as if it were a single command. $ (sort | grep 'Mexico') < massivefile > mex_info $ Question You want to create a file named hostname and containing the text easy1. You use the double pipe to make a command conditional on the unsuccessful execution of a previous command. . The && conditional execution symbol ensures that if the attempt to list the hostname file succeeds.com > hostname Answer The use of the || ensures that the code that writes the output from the echo command to the hostname file will only execute if the attempt to list the hostname file fails.com > hostname cat hostname >> echo easy1. In this example. However.com > hostname cat hostname | echo easy1.easynomad. 2. Option 2 is incorrect. and to change the working directory within the subshell without affecting the parent shell. Which line of code will enable you to do this? Options: 1. This causes the shell to spawn a subshell and execute the command block in the subshell. This allows you to define variables that exist only for the lifetime of the subshell. Commands that execute in a subshell do not affect what's happening in the main shell. 3.

it's advantageous to store the code in a file. This is necessary because some commands run differently in different shell programs. you may need to run larger pieces of code that include several lines or to use the same piece of code many times. . you need to be able to execute shell scripts. 3. They contain commands They have a specific filename suffix They have an introductory line of code that defines them as scripts You can execute them Answer Unlike ordinary ASCII text files. The >> redirector is used to append output to a file. You can store blocks of shell commands in shell scripts. The contents of shell scripts are stored as ordinary ASCII text. Therefore. 2. 4. but you cannot execute them. and have an introductory line of code that defines them as scripts. In such cases.Option 3 is incorrect. However. shell scripts contain commands. Option 4 is incorrect. Storing commands in scripts Command grouping is useful for executing relatively short command-line code that you need to run only once. are executable. The I symbol pipes the output from one command into another command as input. you have to assign executable permissions on script files. 3. The first line in any shell script has to be a special line of code that specifies the particular shell program in which the script must run. Question What do you think distinguishes shell script files from ordinary ASCII text files? Options: 1. You can read and edit ordinary text files. However.

group. you can use it as many times as you like. Once you've created a script and made it executable. If it doesn't. The first line of a shell script identifies the command interpreter. Shell scripts are ASCII text files Shell scripts need to be compiled prior to execution Shell scripts need to have executable permissions set The first line of a shell script is used to identify the command interpreter Answer Shell scripts are ASCII text files that need to have executable permissions set. . Options: 1. or other executable permissions must be set. Question Identify the statements that correctly describe shell scripts. Option 2 is incorrect. Because shell scripts are simple ASCII text files. either one or more of the owner. #! /bin/ksh ls /usr/shared/tours || mkdir /usr/shared/tours touch /usr/shared/tours/tourlist echo tour directory and tourlist file created. #! /bin/ksh This simple example of a script tests whether the directory /usr/shared/tours exists. so they don't contain binary code and aren't compiled.The shell identifier at the beginning of a shell script consists of a hash followed by an exclamation point (#!) ± commonly called a shebang ± and the absolute pathname of the shell program. 4. 2. You can execute it directly from the command line or you can invoke it from inside other scripts. Option 3 is correct. Option 1 is correct. you can easily create them in a text editor such as vi or emacs. Because shell scipts are executed. This example shows the first line of a script that uses the Korn shell. the script creates it. Then it creates a file called tourlist inside this directory and returns a message. 3. Shell scipts are interpreted by the command interpreter.

| Print | Contents | Close | Creating an executable file in UNIX Learning objective . All rights reserved. to run commands in the background. the shell splits it into tokens and processes each token in turn. When you execute a command line. which cause the shell to treat the commands as a single command. Storing commands in scripts | | Summary | Copyright © 2003 SkillSoft. The first line of a shell script consists of a hash symbol followed by an exclamation mark and the absolute path to the command interpreter that will be used to execute the script. You can execute shell scripts directly from the command line and reuse them as often as necessary. and to continue a command over multiple lines. You can join two commands so that the second command will execute only if the first command executes successfully or only if it executes unsuccessfully. For example: #!/bin/bash Summary You can use special characters to join commands on a single command line. SkillSoft and the SkillSoft logo are trademarks or registered trademarks of SkillSoft in the United States and certain other countries. to redirect input and output. Command-line processing | | 2. You can group commands using braces or brackets. You can prevent the shell from recognizing a special character by preceding it with a backslash. Table of Contents | Top of page | | Learning objective | | 1.Option 4 is correct. Command grouping | | 3. All other logos or trademarks are the property of their respective owners. You can store blocks of commands in a text file called a shell script and make this file executable.

After completing this topic. You open a new text file in vi and ± in this case ± name it add_pkg_files. see if you can complete the code that does this. #!/bin/ksh clear echo "Please enter the name of the new travel package: " read PNAME ls /usr/shared/$PNAME || mkdir /usr/shared/$PNAME cd /usr/shared/$PNAME . MISSING CODE Answer You type #!/bin/ksh to invoke the Korn shell at the beginning of the script. and you need to create "bookings" and "info" subdirectories in the package directory. the shell script needs to prompt the user to supply the package name. Assuming that the path to the Korn shell is /bin/ksh. you should be able to create and run a simple shell program. Question You need to invoke the Korn shell at the beginning of the script. You do this using a series of mkdir statements. For example. #!/bin/ksh clear echo "Please enter the name of the new travel package: " read PNAME You need to create a directory for the new package in /usr/shared. Creating a shell script To create a shell script. It then needs to read the name and store it as a variable. let's say that you decide to write a shell script for the Korn shell that automates the repetitive task of creating a file and folder structure for a new travel package. The names you need to use for the new files and directories depend on the names of the travel packages. 1. Therefore. you open a text file in a text editor such as vi or emacs.

This command reveals that the file doesn't have execute permissions set for it. Therefore. #!/bin/ksh clear echo "Please enter the name of the new travel package: " read PNAME ls /usr/shared/$PNAME && mkdir /usr/shared/$PNAME cd /usr/shared/$PNAME mkdir bookings mkdir info touch /bookings/$PNAME_bookings touch /info/$PNAME_accom touch /info/$PNAME_flights echo "Files and folders for $PNAME created in /usr/shared. one for accommodation. You do this using a series of touch statements. you can confirm its existence using the ls -l command. and one for bookings. you can't run it as a script. you've called the script add_pkg_files.mkdir bookings mkdir info You need to create three empty text files in the new folder hierarchy ± one for flights. #!/bin/ksh clear echo "Please enter the name of the new travel package: " read PNAME ls /usr/shared/$PNAME && mkdir /usr/shared/$PNAME cd /usr/shared/$PNAME mkdir bookings mkdir info touch /bookings/$PNAME_bookings touch /info/$PNAME_accom touch /info/$PNAME_flights Finally. In this example. $ ls -l total 2 -rw-r--r-$ 1 vincep vincep 326 Feb 11 11:56 add_pkg_files . you want the script to display a message to the user that confirms that the files and folders have been created successfully." After you've saved and closed the text file containing your new script.

$ chmod +x add_pkg_files $ In numeric form. you use the chmod +x command. you specify permissions using a three-digit octal code. $ chmod 770 add_pkg_files $ Running ls -l again reveals that the script file is now executable. $ ls -l total 2 -rwxrwx--$ 1 vincep vincep 326 Feb 11 11:56 add_pkg_files . and execute permissions respectively. with 0 specifying no access and 7 specifying read. On the other hand. In this case. and x to denote read. you use the letters r. In symbolic form. the second to the owner's group. but you don't want anyone else to be able to write to the script. w. you don't want general users to be able to use the script at all. and the third to all other users. and execute permissions. You can do this by specifying the script's permissions as 755. write. you would need to specify the script's permissions as 770. Let's say that you need to allow everyone to execute a script. The numbers from 0 to 7 represent increasingly open permissions. $ chmod 755 add_pkg_files $ Let's say that you're a member of a group of developers and you want other members of the group to be able to edit your script.When you specify a set of permissions. The first digit applies to the file's owner. To make a script executable using symbolic form. you need to specify the permissions that apply to y y y the file's owner users in the file owner's group everyone else You can specify permissions in either symbolic or numeric form. write.

general access to the file ± as represented by the 0 in the permissions octal ± is denied. but can't write to it or execute it. Options: 1. Any user Only member of the group that owns the file Only the user that owns the file Only users who are logged on locally Answer In this example. 2. 4. In this example. Everyone File owner Group Local login Answer You can assign permissions to the individual user that owns the file. 3. only the file owner has the executable permission assigned ± so only they can run the shell script. File system permissions aren't affected by whether users are logged in locally or remotely. to the group that owns the file. Option 1 is incorrect. Question Identify the levels at which you can assign permissions. so they have full permissions to the file and can execute it.Question If the octal mode value of a shell script's permissions is 740. 4. Option 2 is incorrect. Option 4 is incorrect. and to everyone else. The file owner's permissions are represented by the 7. the permissions of members of the group that owns the file is represented by a 4 so they can read the file. . Option 3 is correct. In this example. 3. 2. who will be able to run the shell script? Options: 1.

preceded by . The script executes in the subshell.Option 1 is correct. the user who creates a file owns it. you can specify its full file path. If you want everyone to be able to read a memo in a shared directory. and specifying the path to the script as well as the script name. This causes the shell to spawn a child shell process. You navigate to the directory in which the script is stored and type its name at the shell prompt. You can set permissions for anyone that tries to access the file. Instead of navigating to the script's directory. and usually has full permissions to the file. you would set the read permission in the third permission set. This allows you to specify shell options. the user who creates a file is part of a primary group that also owns the file You use group permissions to control who can access a file and what they can do with it. This allows you to execute the script by simply typing its name. Option 2 is correct. you type . By default. also called a subshell./. invoking the shell Invoking the shell to execute a script involves running an instance of the shell. using your environment Using your environment to execute a script requires that the script is located in a directory that is found in the $PATH environmental variable. Option 3 is correct. You can't assign permissions at local login level. By default. which returns you to the main shell once the script has finished running./add_pkg_files at the command prompt. To run the add_pkg_files script using direct execution. Option 4 is incorrect. regardless of your current working directory. Running a shell script You can execute a shell script by y y y executing it directly invoking the shell using your environment executing it directly Direct execution is the simplest way to execute a script. . 2. Instead you use the group ownership of files to control access.

What do you think you can use the shell to do? Options: 1. This causes the current main shell to run each command in the script in sequence. you only need to type the name of the script. As with direct execution.) $ source add_pkg_files Question You may not want to execute a script immediately. In some UNIX shells the keyword source is replaced by a period (. $ add_pkg_files If you don't want to run the script in a subshell.profile file. you can precede it with the keyword source. you don't need to use ./add_pkg_files You can run the script in the background. which allows you to use the main shell while the subshell executes the script. To do this in the Korn shell. 4. 2. 3. for example. You can't do anything else with the main shell while the script is executing. you type /bin/ksh add_pkg_files. $ /bin/ksh add_pkg_files If you have added your script directory to the $PATH statement in your . Run a script at a specified future time Run a script regularly at a specified interval Run a script when system load levels are low Run a script when the system is offline Answer ./add_pkg_files & You can run the script by invoking the shell. $ . This causes the script to run in a subshell. In this case. the script runs in a subshell.$ ./ or the shell to run the script.

cron Targets: A. In this example. Runs scripts when system resource usage is low B. or whenever system load levels are low. which starts a process that checks the /etc/crontabs file each minute and executes any jobs scheduled for the current minute. $ cron You use the batch command to run a script as soon as system load levels are low. You use the at command to run a script at a specified future time. Runs scripts at a specified time Answer . You need to make an entry in the /etc/crontab file.You can use shell commands to run a script at a specified future time. you specify that the script must run at 6:00 pm on October 12. $batch add_pkg_files Question Match the commands to their descriptions. When you run a script with the batch command. specifying the name of the script and the interval at which to run it. Then you run the cron command. You can also use more informal time specifications like 1pm tomorrow or even teatime. at 2.5. batch 3. Runs scripts at a specified interval C. Options: 1. the shell queues it as a pending job until the system load average falls below 1. which means 4:00 pm. $ at 6pm Oct 12 add_pkg_files You use the cron command to run a script at regular intervals. at regular specified intervals.

sh file in a subshell.You use the at command to run commands at a schedule time. or specific months. Option 3 is incorrect. which contains a shell script named addfile. The amount will vary according to your system. It is used when the location of the file is not listed in the $PATH variable. Option 1 is incorrect. The . It can be set to recognize minutes./addfile. The at command allows you to specify the time and date at which a script will run. and the batch command to run scripts when the system is relatively idle.sh Answer The source command executes the commands in a target file as if they were entered into the current shell. This method executes the script in a subshell.sh file is listed in the $PATH variable Option 2 is incorrect.sh .sh. Question You have logged in as gregl and navigated to /home/gregl/bin. addfile. You can use a variety of formats. .sh /bin/bash addfile. It's useful if you need to set options for the subshell. The cron command allows you to specify the interval at which a command will repeat. 3. 4. days of the month. This method launches a subshell in which the script is executed. days of the week. Which command should you use? Options: 1. hours. You want to run the script in the current shell. including keywords such as "noon" and "today". the cron command to run commands at a regular interval. It runs commands or scripts when system load levels drop below a specific amount. It is used when the location of the addfile. The batch command is useful if you want to run scripts at times when they won't interfere with system performance. 2.sh source addfile./ syntax only allows you to execute the addfile.

Option 4 is correct. The source command reads the contents of the referenced file directly into the current shell. It's useful if you want to apply changes to your .profile file during your current session.

Summary
To write a shell script, you begin by invoking a shell. Then you add lines of commands that perform the required tasks. You save the file and make it executable by assigning execute permissions to it. You can run a shell script by invoking it directly or by invoking it through the shell. Both these processes cause it to run in a subshell. Alternatively, you can run a script in the main shell by using the source keyword. If you include your script directory in the $PATH statement of the .profile file, you can run a script simply by typing its name at the command prompt.

Exercise: Writing a UNIX shell program
A note about exercises

This exercise is designed for practice use and does not contain new learning content. If your computer doesn't have an application or applications required to carry out the exercise tasks, or if you would prefer to perform the exercise at another time, you can proceed to the next topic. Scenario
You currently use a text file as a signature file for your e-mail messages. It contains your name, job description, and contact details. You decide to liven it up a little by writing a script that customizes it with a different message every day.

Exercise
Your assignment for this exercise is to write a script that customizes your e-mail signature file ± called mysig ± with a random message. You generate the messages using the fortune command, which outputs a random snippet of wisdom each time you run it. The fortune program is located in /usr/games. You don't need to supply any options or arguments to the fortune command. You need to incorporate the fortune message in your signature file. You need to use the cp command to make a temporary copy of mysig called dailysig. This file prevents a buildup

of previous fortune messages by storing a single message for each day only. Finally, you append the output from fortune to dailysig by redirecting to dailysig. The shell you're using for this script is the Korn shell, which is located at /bin/ksh.

Task list
Number 1 Instructions Write a script for the Korn shell that uses the fortune and cp commands ± as well as output redirection ± to customize your e-mail signature file with a random message.

Review your solution and, when you are satisfied with it, open the solution page.

Table of Contents
| Top of page | | Scenario | | Exercise | | Print | Contents | Close |

UNIX command execution
Learning objective

After completing this topic, you should be able to manage the execution of UNIX shell commands.

1. Using the command line
In UNIX, shell programs provide an interface between users and the kernel ± the core of the operating system. You interact with the kernel by entering commands at the shell prompt. It's possible to enter several commands at once. In this case, you separate each command using a semicolon (;). The code shown here redirects the output of the ls command to a file called listing, and then uses the cat command to display the contents of the file. Because the two commands are separated by a semicolon, they run consecutively.

$ ls -l /home > listing ; cat listing lrwxrwxrwx 1 root wheel 9 Oct 30 13:53 /home -> /usr/home $ If you end a line of code with a backslash (\), pressing Enter will move you to a new line and allow you to continue entering commands. You can continue to do this over multiple lines. When you run the commands, the shell will execute your code as if it were one long line, ignoring the backslash characters. You use backslash characters for improved readability. $ echo This is a very long line of \ > text, wrapped with a backslash This is a very long line of text, wrapped with a backslash $

Question
Most shell commands behave as filters ± they can take data as input, process it, and provide output. Because of this behavior, you can chain commands together, piping the output of one command into the input of another command. You do this using the pipe character (|). See if you can pipe the output of the ls -l command to the less command.

$ MISSING CODE

Answer
You type ls -l | less to pipe the output of the ls -l command to the less command. Sometimes you may want to run commands in the background, especially if they're likely to take a long time to complete. Background commands use idle CPU time only, allowing you to get on with other things. You can background any command by suffixing it with an ampersand character (&). The code shown here will run a script called myscript.sh in the background. $ ./myscript.sh & [1] 34030 $

Question
Which statements about using the command line are true? Options: 1. 2. 3. 4. You use a backslash (\) to wrap commands across multiple lines You use a forwardslash (/) to prevent special characters being interpreted You use an ampersand (&) to run commands in the background You use a semi-colon (;) to separate commands that execute consecutively

Answer
You use the backslash to make long commands more readable, the semi-colon to enter consecutive commands on the same line, and the ampersand to run commands in the background. Option 1 is correct. Provided you precede it with a backslash, you can use the Enter key to continue long commands on a new line. The shell will run your command as one long line, ignoring the backslashes. Option 2 is incorrect. The forwardslash does not prevent special characters from being intepreted. It is used in the syntax for describing the filesystem. Option 3 is correct. The ampersand allows you to run commands in the background on idle processor cycles, leaving you free to continue working in your current session. Option 4 is correct. You can use the semi-colon to combine commands that execute consecutively on a single command-line. This is useful when the first command will take a long time to complete.

2. Conditional execution
Conditional execution is a programming strategy that allows you to specify different actions based on the outcome of an initial operation. For example, you could create a shell script that checks the size of a log file and then backs it up only if it is larger than a certain size. Regardless of their type or function, most UNIX commands return an exit status number to the shell when they've completed executing. The exit status indicates whether a command executed successfully. If a command executed successfully, it returns a value of 0 to the shell. Greater values indicate an error of some sort.

double ampersand (&&) If you separate two commands with two ampersand characters (&&). . For example. while an exit status of 0 indicates that it did complete successfully. Options: 1. Question Identify the statements that correctly describe conditional execution. in the syntax shown here. Conditional execution allows you to choose what code to run based on the output of a command Answer A non-zero exit status indicates that a command did not execute successfully. you can use them to include conditional decisions in your shell scripts. An exit status of 0 indicates that a command completed successfully 3. Any non-zero exit status is a failed command. Option 1 is correct. And if the second command fails. the third command will not run. It's possible to combine conditional execution operators to produce complex code.Although you never see exit statuses at the shell prompt. Most shells provide at least the following two pairs of operators for performing conditional execution based on exit status values: y y double pipe (||) double ampersand (&&) double pipe (||) If you separate two commands with two pipe characters (||). Conditional execution allows you to choose an action based on the exit status of a command 4. the second command will execute only if the first command exits successfully ± returning a zero exit status. and the shell you use. A non-zero exit status indicates that a command did not execute successfully 2. The range of possible non-zero values for the exit status depends on the command that you execute. Conditional execution allows you to choose an action based on the exit status of a command. the second command will execute only if the first command returns an error ± a non-zero exit status. the second command executes only if the first command fails.

as well as the command that prints the contents of the renamed file. Depending on the conditional operator you use. touch hosts oldhosts && cat oldhosts && touch hosts Answer The || operator ensures that the hosts file is not overwritten if it already exists. Option 1 is incorrect. Which commands are safe to use? Options: 1. 3. or only if the previous command fails. The ls hosts command will have an exit status of 0 if the host file exists. Option 2 is correct. . code will execute only if the previous command executes successfully. and you don't want to alter any existing files. Option 4 is correct. will be 0. It is safe to overwrite the hosts file if the command that renames the original file. The execution of the command to overwrite the hosts file is not dependant on the exit status of the command listing the host file. not their results. 4. This will cause the touch command to execute and create a new hosts file. Option 4 is incorrect. Option 3 is correct. operator merely allows consecutive execution of commands. but conditional execution only operates on the exit status of commands.Option 2 is correct. If the last command to execute completed successfully. You use the && operator to ensure that a new hosts file is only created if the command to rename the original succeeds. You can use the test command to return an exit status after testing for a particular value. Option 3 is incorrect. in which the exit status is stored. Question You are creating a script that writes to the filesystem. The || operator will execute if the hosts file doesn't exist and the ls command returns a non-zero exit status. The . and the && operator will cause the hosts file access and modification times to be updated. 2. the value of the $? Variable. complete successfully. ls ls ls mv hosts hosts hosts hosts && touch hosts || touch hosts .

3.. If the copy operation fails. If the file exists. Grouping commands Conditional execution operations are based on the exit status value of a single command ± you can't have more than one command on either side of a conditional operator. Question See if you can complete the code shown here to send an e-mail to the root user if the copy operation fails. .txt Answer You use the || operator to execute the mail root@localhost "copy operation failed" command if the copy operation returns a non-zero exit status. $ ls -l /var/log/mylog MISSING CODE cp /var/log/mylog /backup/mylog \ MISSING CODE mail -s "Error" root < errmsg. the system should send an e-mail to the root user.txt Answer You use the && operator to run the cp /var/logs/mylog /backup/mylog command if the ls /var/logs/mylog command locates a log file. $ ls -l /var/log/mylog && cp /var/log/mylog /backup/mylog > MISSING CODE mail -s "Error" root < errmsg. command 1 || command 2 && command 3 Question Let's say that you want to create a command that will check for the existence of a log file. See if you can type an operator in the first blank space that will back up the log file if it exists. the log file should be copied to a backup directory.

The ls command will list the contents of the /etc directory 3. The ls command will execute on condition that the cat hosts command is successful 4. You can enclose a series of commands in brackets to create a code block. The advantage of running commands in a subshell ( by grouping them using round brackets ( is that subshells have their own environment variables. The shell will treat a code block as if it were a single command ( it will return one exit status value for the entire block. You achieve this using grouping.This behavior is sufficient for simple tasks. Question Which statement about the line of code shown here is true? (cd /etc . rather than for each individual command that the block contains. . any radical environment changes that take place during the running of a code block don't affect the shell you started with. You can group commands using the following two types of brackets: y y braces ({}) round brackets (()) braces ({}) You can use braces ({}) to create blocks of code that will execute in your current shell. round brackets (()) You can use round brackets (()) to create blocks of code that will execute in a subshell ( a new shell program spawned from the shell that you're running. This allows you to create far more complex commands and shell scripts. The code in parentheses is a comment Answer Code within parentheses is executed in a subshell. cat hosts) && ls $ (cd /etc . cat hosts) && ls Options: 1. but often you'll need to base conditional execution on the result of a series of commands. As a result. The code in parentheses executes within a subshell 2.

Answer You use the parentheses () and the braces {} operators to group commands in code blocks that return a single exit status. The variable that stores the current working directory for the shell in which the ls command is executed is not affected by the command to move to the /etc directory in the subshell. Option 2 is incorrect. The execution of the ls command is conditional on the successful completion of the entire block of code within parentheses. The . 3. You can include comments in shell scripts by preceding each line of comments with the # symbol. for instance. Option 2 is correct. Option 4 is incorrect. 2. The {} symbols group commands into a single code block for execution in the current shell. 4. Code within parentheses is run as a separate process in a subshell. Options: 1. Option 1 is incorrect. The [] symbols are used by the shell in pattern matching operations to specify character ranges. However. [] {} () . Option 3 is incorrect. You can set local environment variables within the subshell without effecting your main shell session. Option 4 is incorrect. Question Identify the operators that allow you to group commands in code blocks. The () symbols group commands into a code block that is executed in a subshell. This is useful if you want to avoid altering environment variables in your current shell.Option 1 is correct. Question . the commands are executed in sequence. not as a code block. Option 3 is correct. symbol is used to enter multiple commands on the same line.

it has no effect on the current shell you're in. and round brackets (()) to specify that code execute in a subshell. Option 3 is incorrect. ls mylog && echo "Found the log file" The command that changes the current working directory to /var/log is part of a code block enclosed in brackets (()). your current working directory will still be /home/gregl. At no point does any code change the directory to /usr/home ± either in the current shell or the subshell ± so this can't be the current directory. It looks for a specific log file. Summary The shell's command line provides an interface between users and the UNIX kernel. ls mylog } / && echo "Found the log file" Options: 1. /usr/home Answer After the command runs. You can separate commands using a semicolon (. and plug them into each other using a pipe (|). continue them on new lines using a back slash (\). Option 1 is incorrect. To run the code in the current shell. and if the file exists a message displays. you need to remove the braces. The command that changes the directory to /var/logs runs in a subshell.Suppose that you're in /home/gregl and you need to execute the code shown here. You use two ampersand characters (&&) to specify that a command run only if a previous command was successful. You can group commands into code blocks to specify that the shell return one exit status for the entire block. so it will execute in a subshell. You use braces ({}) to specify that code execute in the current shell. as shown here: cd /var/log . thereby changing the current directory. /var/log 2.). and two pipe characters (||) to specify that a command run only if a previous command failed. As a result. . You can use conditional operators to specify that commands execute based on the exit status of other commands. /home/gregl 3. What do you think your current working directory will be when the code has finished executing? $ { cd /var/log .

Table of Contents
| Top of page | | Learning objective | | 1. Using the command line | | 2. Conditional execution | | 3. Grouping commands | | Summary |
Copyright © 2003 SkillSoft. All rights reserved. SkillSoft and the SkillSoft logo are trademarks or registered trademarks of SkillSoft in the United States and certain other countries. All other logos or trademarks are the property of their respective owners.

| Print | Contents | Close |

Redirection in UNIX
Learning objective

After completing this topic, you should be able to redirect standard input and output, and use file descriptors.

1. Using standard I/O redirection
Most UNIX commands behave as filters ± they can take input, process it in some way, and provide output. A shell usually sends this output to the screen, but you can redirect it to provide advanced functionality. A common example of redirection is the use of the pipe operator (|) to plug the output of one command directly into the input of another command. However, redirection most often involves writing to and reading from files. You can perform redirection with files by preceding a filename with one of the following operators: y y y greater than (>) less than (<) two greater than symbols (>>)

greater than (>)

You use the > operator with a filename to redirect the output of a command to a file. If the file doesn't exist, the shell will create it. If it exists, the shell will overwrite it. less than (<) You use the < operator with a filename to redirect standard input from a file. For example, when using the mail command to send e-mail, you can redirect input from a file you have previously prepared, rather than having to type your message at the shell prompt. two greater than symbols (>>) You use the >> operator with a filename to redirect the output of a command to a file, appending the new data if the file already exists. This is useful for creating log files. If you use a lot of file redirection in your scripts, it's quite easy to overwrite existing files accidentally. To prevent this, most shells implement the noclobber environment variable. When set, noclobber prevents file overwriting through redirection ± but not through the execution of commands such as cp or rm. You enable noclobber by typing set -o noclobber, as shown here. If you want to overwrite output files protected by noclobber, you can use the >| operator to do this. $ set -o noclobber $

Question
Let's say that you want to send e-mail to a user called vincep. You've used the vi editor to type the body of the e-mail, and you've saved it to a file called email.txt. See if you can complete the code shown here to redirect input from the email.txt file rather than from standard input.

$ mail ±s "Guess what" vincep@localhost MISSING CODE email.txt

Answer
You use the < operator to redirect input from a file rather than from standard input. You send the mail, and the shell reads the e-mail body from the text file you've specified.

$ mail ±s "Guess what" vincep@localhost < email.txt $

Question
Let's say you're using the man command to find out about the exec command. You'd like to dump the information to a file so that you can print it later. See if you can complete the command shown here to dump the output of the command to a file called exec.txt.

$ man exec MISSING CODE exec.txt

Answer
You use the > operator to redirect standard output to a file rather than to the screen. The shell dumps the output of the man exec command to a text file. Because you've redirected the output, you don't see it echoed to the screen. $ man exec > exec.txt $

Question
Match the redirection operators to the descriptions of their function. Options: 1. > 2. < 3. >> Targets: A. Used to append output from a command to a file B. Used to redirect output from a command to a file C. Used to specify a file as input for a command

Answer
You use the > operator to redirect the output from a command to a fle, the < operator to use a file as input for a command, and the >> operator to append the output from a command to an existing file.

You can use redirection to document your system by redirecting the output from commands to a file, as in this example, which records the network interfaces configured for a system: ifconfig ±a > network.txt Several UNIX commands accept files as input. For instance, you can redirect a text file called report.txt to the mail utility and send it to Fred with the following command: mail Fred < report.txt Appending command output to an existing file is useful for troubleshooting. Scheduling regular execution of the following command enables you to monitor which kernel modules are loaded on a Linux system: lsmod >> /var/modules.log

2. File descriptors
File descriptors are files ± usually with numeric filenames ( on disk that point to input/output (I/O) objects, such as the keyboard, the screen, or other files. You can think of them as placeholders. By using file descriptors, processes don't have to interact mechanically with the I/O objects that the descriptors represent ± the kernel handles these mechanics. Any running process can expect at least the three following default file descriptors to be available: y y y 0 Descriptor 0 is also known as standard input. It's normally mapped to the keyboard. Processes look to this descriptor for user input. 1 Descriptor 1 is also known as standard output. It's normally mapped to the screen, although when UNIX was created it was mapped to a printer. Processes write command output to this descriptor, and the output then appears on your screen. 2 Descriptor 2 is also known as standard error. It's normally mapped to the screen, but when UNIX was invented it was mapped to a dedicated printer. 0 1 2

As with ordinary redirection. To change this default behavior and not have the file overwritten. >&n You use >&n to redirect standard output to another descriptor. n>> filename You use n>> with a filename to redirect a descriptor to the specified file. Processes can also create their own descriptors. this will append to an existing file. Options: . <&n >&n n< filename n> filename n>> filename n>| filename Question Identify the true statements about performing descriptor redirection. usually for interacting with files. For example. set the noclobber variable. n> filename You use n> with a filename to redirect a descriptor to the specified file. as with ordinary redirection. using the following syntax ± where n is a file descriptor: y y y y y y <&n You use <&n to redirect standard input from another descriptor. using the set noclobber command. n>| filename You use n>| with a filename to redirect a descriptor to the specified file. n< filename You use n< with a filename to redirect a descriptor from the specified file. this will overwrite an existing file.Processes write error messages to this descriptor. overriding the noclobber variable if this has been set. you could type <&2 to feed standard error into standard input. For example. you could type >&2 to send standard output into standard error. and the messages then appear on your screen. You can redirect file descriptors in a similar way to performing ordinary redirection. This will redirect to a file but.

You use 2>| to ensure that existing files aren't overwritten by redirected standard error 2.txt Answer You type > to redirect standard output to a file.txt . Instead of the output going to the screen it can be redirected to a file using 1> Question Let's say that you want to use the find command to locate reports.txt. Option 3 is correct. You use 2> to redirect standard error to a file 3. See if you can complete the first part of the code shown here to redirect standard output to a text file called output.1. Option 4 is correct. this option allows you to overwrite existing files with standard error. Use 1> to redirect standard output to a file Answer You use >&2 to redirect standard output to standard error. and you redirect standard output to a file with 1>.txt. you redirect standard error with 2>.txt MISSING CODE error. You use >&2 to redirect standard output to standard error 4. Question See if you can complete the code shown here to redirect standard error to a file called error.txt MISSING CODE error. This is useful for for printing error messages. this would be a quick way of printing command output. $ find / -name "report*" MISSING CODE output. Option 1 is incorrect. In fact. Option 2 is correct. and you want to redirect both standard output and standard error to text files. If your standard error is connected to a printer instead of the display. $ find / report* 1> output.

Question Match each standard file descriptor value to its name. Here documents make it possible to give batch input to a command ± to pass the command a list of things you want it to do. you may want to pass multiple lines of input to a command. the descriptor for standard output has a value of 1. Scripting with redirection Sometimes. and is usually mapped to the screen ± but it is sometimes useful to map it to a printer. Standard input C. 2 Targets: A. You do this using a here document. to record errors. 3. 0 2. and the descriptor for standard error has a value of 2. Standard input is associated with file descriptor 0. 1 3. Standard error B. Typing commands with a keyboard is the most common way of interacting with the shell.Answer You type 2> to redirect standard error to a file. Standard error is associated with file descriptor 2. Options: 1. You can use here documents using either of the following two syntax forms: . Standard output Answer The file descriptor for standard input has a value of 0. and is usually mapped to the keyboard. Most programs use standard output to print usage messages or the results of commands. Standard output is usually mapped to the screen. for convenience.

command <<. using the word END as a terminator. So you enter the full command to open a session to that machine and then press Enter. $ telnet << END > open 190. and the shell waits for further input. The trailing dash in the syntax causes all leading tabs in the subsequent input to be stripped.terminator [input «] When you use the syntax command <<. until it reaches the word or character you specified as a terminator. the shell executes the command and passes it the input you specify ( line by line.3 > gregl password .2.3 in this case.2. You press Enter. You begin by setting up the telnet command with a here document.100. the shell executes the command and passes it the input you specify ( line by line. Then you press Enter. $ telnet << END > The first thing that a telnet session needs is the address of the target machine ( 190. so you type them on the next line.2.100.terminator [input]. . $ telnet << END > open 190. In this case. until it reaches the word or character you've specified as a terminator.3 You know that the remote machine will require a username and password.terminator [input «] command << terminator [input «] When you use the syntax command << terminator [input]. your username is "gregl" and your password is simply "password".y y command << terminator [input «] command <<. Let's say that you want to automate a telnet session to e-mail yourself some data off a remote machine.100.

3 > gregl password > mail ±s "remote userlogs" gregl@190.1 < /var/log/userlog quit To finish and execute the here document.100.2.3 gregl password mail ±s "remote userlogs" gregl@190.100. The shell executes the telnet command and feeds it the here document line by line. See if you can complete the code shown here to ensure that any leading tabs in the here document will be stripped out. $ ssh MISSING CODE Finish Answer You use the <<.2. the word END ± and you press Enter. using the word "END" as a terminator. You press Enter after each command. you enter the terminator that you specified to begin with ( in this case.operator to ensure that leading tabs are stripped out of here documents.The remote system should have logged you on by this point in the script. $ > > > > telnet << END open 190.2. Question Which statements about here documents are correct? Options: . $ telnet << END > open 190.100.100. so you enter the commands you need to fetch the file you want.2.1 < /var/log/userlog > quit > END Question Suppose that you're setting up a here document to run an ssh command. You also enter the quit command to end the telnet session.

3. The terminator in here documents is END Answer You use the <<. accepting input and providing processed output. Automatically stripping tabs from your here document allows you to improve its legibility. Using standard I/O redirection | | 2. You can redirect command output to a file. Option 4 is incorrect. and standard error (2).operator allows you to strip leading tabs from a here document Here documents can be used to automate login processes The first line of a here document is always a command.1. They are most commonly used for setting up scripts for interactive commands such as telnet. File descriptors | . such as telnet or ftp. 2. 4. Here documents start with a command interpreter that loads a command to read and execute the rest of the shell script. Here documents provide a convenient way of sending batch input to a command. Summary Most UNIX commands behave as filters. You can redirect file descriptors. Here documents are often used to automate interactive logins and the first line of a here document is always a command. Most interactive command line programs. can be automated using here documents Option 3 is correct. standard output (1). The <<. Option 2 is correct. Although END is frequently used as a terminator in here documents.operator to strip leading tabs from lines in a here documents. and you can redirect command input from a file. File descriptors are numeric placeholders for input/output (I/O) objects. Table of Contents | Top of page | | Learning objective | | 1. Option 1 is correct. you can use any string as a terminator. The default file descriptors present in any shell environment include standard input (0).

You can specify limited lists of characters for filename substitution using square brackets ([]). you should be able to use substitution and quoting to expand and match files and commands. which it then passes to the command you're trying to execute. or with a pattern fragment. For example. the shell will return a list of every file in your current working directory with a name beginning with "w". The wildcard characters that UNIX supports include y y asterisk (*) question mark (?) asterisk (*) You use the * wildcard to match a string of any length. | Print | Contents | Close | Substitution and patterns in UNIX Learning objective After completing this topic. Filename substitution involves using wildcard characters either on their own. SkillSoft and the SkillSoft logo are trademarks or registered trademarks of SkillSoft in the United States and certain other countries.| 3. Substitution and matching You can use filename substitution when entering commands to specify groups of files that you want to work with. 1. question mark (?) You use the ? wildcard to match a single character. All rights reserved. if you specify w*. if you specify file0?. For example. All other logos or trademarks are the property of their respective owners. the shell might return a list containing file01 through file09 ± if these files existed. Scripting with redirection | | Summary | Copyright © 2003 SkillSoft. The shell resolves a wildcard to a list of files. using one of the forms shown here: .

log2. log7. the shell will return a list containing log1. In the filename substitution shown here. the shell will return a list containing data_a. Question See if you can complete the code shown here to retrieve a list of all the files in the current directory that begin with a lowercase letter or a digit. You can include any number of ranges in this way. file04.txt report3. [a-d] You use the form [a-d] to perform substitution with any character that appears in the range between the square brackets. if you specify data_[a-c]. log6. if you specify log[1-36-8]. the shell will return a list containing file01. For example. if you specify file0[147]. which allows any type of string to follow the specified ranges. $ ls MISSING CODE Answer You type [a-z0-9]* or [0-9a-z]* to retrieve a list of all files that begin with a lowercase letter or a digit. the square brackets hold two ranges ± a to z and 0 to 9. The brackets are followed by an asterisk (*). and log8 ± if these files exist. For example. and data_c ± if these files exist. For example. data_b. [a-ce-g] You use the form [a-ce-g] to perform substitution with any character that appears in any of the ranges between the square brackets. and file07 ± if these files exist.y y y [abc] [abc] [a-d] [a-ce-g] You use the form [abc] to perform substitution with any character that appears between the square brackets. log3. $ ls [a-z0-9]* 120415_log report1.txt staffdata .

txt report3.txt staffdata 120603_log report2. For example. ~The shell resolves ~. ~+ The shell resolves ~+ to the path of the current directory. $ echo ~ /home/vincep $ You can use the tilde (~) character in substitution in the following forms: y y y y ~ The shell resolves a lone tilde to the value of the current user's $HOME environment variable.120603_log report2.txt searchdata $ You can perform reverse matching using the exclamation mark (!) character. $ ls ±l *[!0-9] 120415_log report1.to the path of the previous directory you were working in. This enables you to write scripts with path references that any user can run. the code shown here lists all files in the current directory that don't end in a digit. ~user The shell resolves ~user to the path of a specific user's home directory. ~ ~user ~~+ Question Which commands use the tilde (~) correctly? Options: .txt searchdata $ Occasionally. You can refer to a user's home directory without knowing their username using the tilde (~) character. you may need to refer to a user's home directory in a script.

You can also specify a range using the [a-e] format. Substitutes for any character in a list B. Substitutes for any character in a range C. . Using the tilde command in this context changes the current directory to its previous value. [abc] [a-e] * ? Targets: A. while the ? matches any single character. Question Match each filename substitution format with its description.1. cd cd cd cd ~ ~$HOME ~~Fred Answer These commands all use tilde substitution correctly Option 1 is correct. 3. In this circumstance. 2. In this case. Option 2 is incorrect. The * substitutes for any character zero or more times. you use the [abc] format. Options: 1. 2. 3. Option 4 is correct. 4. the tilde command changes the current directory to the home directory of the user Fred. 4. The tilde substitutes for the $HOME variable. Substitutes for zero or more characters Answer To substitute from a list of characters into a filename. the command changes the directory to the home directory of the current user. so this command wouldn't work. Option 3 is correct. Substitutes for any single character D.

text. The command ls file? will match and list any file with a filename that starts with file and has one additional character. such as file1 or filea if they exist. text.c.The command ls file[abc] would use filename substitution to match and list files named filea. It then passes this command's entire output to the unbracketed command. the shell reads the specified file and passes its entire contents to the command.b.[a-e] matches and lists every file named text with a suffix consisting of a period followed by a character in the range of letters from a to e. Command substitution Command substitution allows you to use the output of one command as an argument for another command. text. The command ls file* will match and list any file with a filename that starts with file. and filec if they exist.a. $ ls ±l | grep MISSING CODE Answer The $(whoami) command returns your current username. text. without knowing what your username is. .e will be listed.d. including file123. You can perform command substitution using the syntax y y $(command) $(< filename) $(command) When you use $(command) as an argument for another command. $(< filename) When you use $(< filename) as an argument for a command. which the grep command uses to filter the output of the ls ±l command. text. In other words. Question See if you can complete the command shown here to display a list of files that belong to you. The command ls text. the shell executes the bracketed command first. fileb. 2.

$ echo '*' * $ Instead of quote marks. $ ls ±l | grep $(whoami) -rw-r--r-. The code shown here displays an asterisk on the screen. Which commands use a suitable alternative method for escaping special characters? Options: .The code shown here shows a list of the files in the current directory that you own. you must prevent the shell from interpreting it by quoting the character. The code shown here uses backslash escaping to print out the message. Instead.txt When you include a special character such as a wildcard or a pipe as part of an argument for a command. Without the quotation marks. "'*' is a special character. the shell would have resolved the asterisk to a list of all the files in the current directory.1 vincep vincep -rw-r--r-.1 vincep vincep -rw-r--r-. This instructs the shell to pass the character literally to the command instead of trying to interpret it." $ echo \'\*\' is a special character '*' is a special character $ Question If you need to pass special characters to a command in an argument. the command does not interpret that character. Backslash escaping is also useful for situations in which you need to pass an actual quote mark as an argument. To do this. you enclose them in quotes to prevent them from being interpreted. the shell resolves it and passes the output to the command as an argument. you can use backslash escaping to perform quoting.1 vincep vincep -rw-r--r-.txt Jan 8 09:23 report2.1 vincep vincep 9880 9372 73234 247416 451008 Feb 11 15:40 120415_log Feb 11 15:41 120603_log Jan 8 09:22 report1.txt Jan 8 09:24 report3. you place a backslash (\) immediately before a special character.1 vincep vincep -rw-r--r-. If you intend a command to use a special character as an argument.

Option 3 is incorrect. Using substitution in a script Let's say that you're a system administrator. Option 1 is correct.1. 3. #!/usr/local/bin/ksh # Logon welcome script clear echo Welcome $(whoami) echo The current date is $(date "+%d-%M-%Y") Question You want to display a list of all the reports in the user's home directory. echo $(< $)USER Answer You use the backslash to escape special characters. The backslash prevents the $ from being interpreted as a special character. Option 2 is incorrect. You start the vi editor. but you don't know what the user's username is. The $(command) syntax allows you to pass the output from a command as a parameter to another command. You begin the script by clearing the screen and you use command substitution to greet the user using the whoami command. and you're preparing a startup script that will run each time a user logs in. go into insert mode. and begin typing. echo \$USER 2. rather than the value of the $USER variable. echo $($)USER 3. so $USER will be printed onscreen. . The $(< filename) syntax allows you to pass the contents of a file as a parameter to a command. #!/usr/local/bin/ksh # Logon welcome script clear echo Welcome $(whoami) You add a line that uses command substitution to display the current date.

Question You use the ls command to list the contents of the user's home directory.txt -rw-r--r--1 vincep vincep 247416 Jan 8 09:23 report2. See if you can complete the code shown here to use the grep command to filter the output of the ls command to show only those files whose names begin with "report". #!/usr/local/bin/ksh # Logon welcome script clear echo Welcome $(whoami) echo The current date is $(date "+%d-%M-%Y") MISSING CODE Answer You type cd ~ to navigate to a user's home directory without knowing the user's username. You test the script. Welcome vincep The date is 26-08-2003 You have the following reports: -rw-r--r--1 vincep vincep 73235 Jan 8 09:22 report1. . #!/usr/local/bin/ksh # Logon welcome script clear echo Welcome $(whoami) echo The current date is $(date "+%d-%M-%Y") cd ~ ls -l | grep "MISSING CODE" Answer You type report* to have the command return all files that begin with "report".txt Question Identify the true statements about command substitution and wildcards. and it runs successfully.Complete the code shown here to navigate to the user's home directory.

The command echo It is $(date). Command substitution allows you to use the output from a command as standard input for a second command 2. provides the following output: It is Fri Aug 18 11:25:55 BST 2003. Option 3 is incorrect. Similarly. Wild cards are used to perform command substitution 4. The shell resolves the argument command first and passes its output to the main command. Wild cards are used to perform filename substitution Answer You use command substitution to include the output from a command in an argument to another command and you perform filename substitution with wildcards. The shell resolves a wildcard into a list of files that match specified search criteria. The command echo It is $(dat*) will yield a "command not found" error message. Command substitution allows you to use the output from a command as part of the argument for another command 3. Redirecting standard output into the standard input of a command is performed using the UNIX pipe facility. Filename substitution provides a quick way of searching large directories for files conforming to a specific pattern. Option 1 is incorrect. Option 2 is correct. Table of Contents | Top of page | . Most shells let you use wildcards like asterisk (*) or a question mark (?) in filename substitution. for instance. You can use any combination of filename substitution and command substitution when you write shell scripts. you can perform command substitution to use the output of one command as an argument for another command. The shell only performs filename substitution with wildcards. Option 4 is correct.Options: 1. Summary Filename substitution involves specifying groups of files to use as arguments for commands.

&& You use the double ampersand operator in the form command1 && command2 . the second command executes only if the first command fails. SkillSoft and the SkillSoft logo are trademarks or registered trademarks of SkillSoft in the United States and certain other countries.| Learning objective | | 1. UNIX command syntax reference Abstract This article serves as a quick reference for the most commonly used shell scripting syntax. All other logos or trademarks are the property of their respective owners. Introduction There are hundreds of UNIX commands that you can execute at the shell prompt. Conditional execution operators || You use the double pipe operator in the form command1 || command2 In the above syntax. Shells have their own built-in syntax that helps you to work more effectively with existing commands by allowing you to perform functions like plugging commands into each other and controlling the flow of execution. All rights reserved. Substitution and matching | | 2. Using substitution in a script | | Summary | Copyright © 2003 SkillSoft. Command substitution | | 3.

the shell creates the file.In the above syntax. >| You use this operator to redirect command output to a file. () You can enclose multiple statements in round brackets to create a code block. the shell creates the file. The shell returns one exit status value for the entire group. the shell appends the new data to the end of it. . the shell overwrites it with the command output unless the noclobber environment variable is set. >> You use this operator to redirect command output to a file. If the specified file doesn't exist. the shell overwrites it with the command output even if the noclobber environment variable is set. the second command executes only if the first command executes successfully. Command grouping operators {} You can enclose multiple statements in braces ({}) to create a code block. If the file does exist. If the file does exist. If it does exist. This code block functions in the same way as a code block enclosed in braces. I/O redirection operators > You use this operator to redirect command output to a file. If the file doesn't exist. rather than for each command in the block. If the specified file doesn't exist. but runs in a subshell. the shell creates the file. < You use this operator to redirect command input from a file.

this will not overwrite an existing file. This will redirect to a file but. Unlike ordinary redirection. unlike ordinary redirection. Filename substitution * You use the * wildcard to match a string of any length. n< filename You use this operator with a filename to redirect descriptor n from the specified file. this will append to an existing file.File descriptor redirection operators <&n You use this operator to redirect standard input from file descriptor n. n>| filename You use this operator with a filename to redirect descriptor n to the specified file. overriding the noclobber environment variable if it is set. ? You use the ? wildcard to match a single character. . n> filename You use this operator with a filename to redirect descriptor n to the specified file. n>> filename You use this operator with a filename to redirect a descriptor to the specified file. >&n You use this operator to redirect standard input to file descriptor n.

~+ You use the ~+ operator to instruct the shell to return the full path of the current working directory. [a-c1-3] You use square brackets to match only characters that appear inside the specified set. ~- . you can specify multiple ranges. Tilde substitution ~ You use the ~ operator to instruct the shell to return the value of the $HOME variable. The shell returns only filenames that don't match the pattern. [a-c] .[abc] . ~username You use the ~ operator with a username to instruct the shell to return the full path of a specific user's home directory. For increased convenience. $(< filename) You use this form of command substitution to pass the entire contents of a file to a command as an argument. !pattern You use the ! operator with a pattern to perform a reverse match. Command substitution $(command) You use this form of command substitution to resolve a command and pass its output to another command as an argument.

\ You use a backslash to allow you to press Enter and continue typing commands on a new line. They also allow you to perform filename. Using a backlash in this way is known as backslash escaping. The shell will execute each command successively once you press Enter. file descriptor redirection. and command grouping. If you enter several commands on the same line. but they also have built-in functions to help you use shells more effectively. Miscellaneous syntax . & You add a single ampersand at the end of a command to run that command as a background process. This is useful for tasks that are likely to take a long time to complete.operator to instruct the shell to return the full path of the previous working directory you used. tilde. input/output (I/O) redirection. The shell will only begin executing your commands when you press Enter on a line that doesn't end in a backslash. Table of Contents | Top of page | | Abstract | | Introduction | . Summary Shell programs can execute a wide range of UNIX commands. and command substitution. you need to separate the commands with semicolons. Most shells support standard operators for conditional execution.You use the ~.

and e-mail that file to the root user. All other logos or trademarks are the property of their respective owners. you should be able to write a shell script that uses the shell's command execution and substitution capabilities. output the search results to a file. If an error occurs. the script should display a message on the screen. SkillSoft and the SkillSoft logo are trademarks or registered trademarks of SkillSoft PLC in the United States and certain other countries. | Print | Contents | Close | Using UNIX commands in a script Learning objective After completing this topic.| Conditional execution operators | | Command grouping operators | | I/O redirection operators | | File descriptor redirection operators | | Filename substitution | | Command substitution | | Tilde substitution | | Miscellaneous syntax | | Summary | Copyright © 2003 SkillSoft PLC. Exercise overview In this exercise. This involves the following tasks: y y y using code blocks using substitution using redirection and conditional execution . All rights reserved. you're required to complete a script that will perform a search for certain types of files.

3. Step 1 of 1 You want the first two lines of the script to act as a distinct code block that returns one exit value for both commands. Option 1 is incorrect. 4. mail -s "local reports" root MISSING CODE localreports . Which type of brackets should you use to achieve this? MISSING CODE ls -l report MISSING CODE MISSING CODE localreports . as in the variable assignment command shown here: DATE=$(date) Option 2 is incorrect. such as: if [ $FEEDBACK = y ] then echo "proceed" else exit fi .Task 1: Using code blocks Let's say that you're the root user and that you're editing a script in the vi editor. The commands should execute in the current shell. You use round brackets to perform command substitution. Round brackets (()) Square brackets ([]) Braces ({}) Less than and greater than signs (<>) Result You use braces ({}) to create a code block that will execute in the current shell. You use the square brackets to enclose conditional expressions. MISSING CODE MISSING CODE echo An error occurred during search operation Options: 1. 2.

Task 3: Using redirection and conditionals Step 1 of 3 Suppose that you want to redirect the output of the ls command to a file named localreports. mail -s "local reports" root MISSING CODE localreports .Option 3 is correct. Use substitution to complete the search criteria shown here. { ls -l report MISSING CODE MISSING CODE localreports . The syntax for a function ± a sequence of code that is available to the shell into which it is read ± is: function_name() {commands} Option 4 is incorrect. They are also used as conditional operators (less-than and greater-than) within conditional expressions. Type the symbol that will achieve this. } MISSING CODE echo An error occurred during search operation Result You specify report[0-9] with the ls command to list all files that begin with the word "report" and end in a number between 0 and 9.mail -s "local reports" root MISSING CODE l ocalreports . The <> special characters are used to perform redirection. Task 2: Using substitution Step 1 of 1 Suppose that you want to use the ls command to search for all files that begin with the word "report" and end in a number between 0 and 9. } MISSING CODE echo An error occurred during search operation Result . { ls -l report[0-9] MISSING CODE localreports .

output the search results to a file named localreports. mail -s "local reports" root MISSING CODE localreports . Step 3 of 3 You want the last line of the script to execute only if the code block produces an error. mail -s "local reports" root < localreports . you want to redirect the contents of a mail from the localreports file. { ls -l report[0-9] > localreports . } || echo An error occurred during search operation . Step 2 of 3 In the second line of the script.You use the greater than symbol (>) to redirect output to a file. Type the correct symbol to do this. mail -s "local reports" root < localreports . It will also display an error message if the code fails. { ls -l report[0-9] > localreports . { ls -l report[0-9] > localreports . Type the symbol that will do this. in this case. You've now successfully completed a script that will perform a search for specific files. a command block ( fails. } MISSING CODE echo An error occurred during search operation Result You use the double pipe symbol (||) to execute a command only if the preceding command ( or. and e-mail the localreports file to the root user. } MISSING CODE echo An error occurred during search operation Result You use the less than symbol (<) to redirect input from a file.

All rights reserved. $ export DEST $ . Local variables are available only in the function or subshell in which they were created or declared. SkillSoft and the SkillSoft logo are trademarks or registered trademarks of SkillSoft in the United States and certain other countries. 1. In this example.Table of Contents | Top of page | | Learning objective | | Exercise overview | | Task 1: Using code blocks | | Task 2: Using substitution | | Task 3: Using redirection and conditionals | Copyright © 2003 SkillSoft. | Print | Contents | Close | Working with UNIX variables Learning objective After completing this topic. Global variables are available throughout the shell. thus making it a global variable. the code exports the local variable DEST from a subshell. You can turn local variables into global variables by exporting them using the export command. including all its subshells and functions. All other logos or trademarks are the property of their respective owners. you should be able to use variables in UNIX programming. Variables and data types Variables are named spaces used to store data.

TC shell The TC shell supports string. Korn shell variables can be either local or global.Like most programming languages. Data types define the types of data contained in variables. Bash shell . Bash shell The Bash shell supports string and integer variables. Options: 1. the Korn shell supports string. The more advanced UNIX shells support four data types: y y y y strings. integer. All variables in the Bourne shell are global. Question Match the UNIX shell type to its description. the shell performs faster arithmetic with integer variables. which are sequences of alphanumeric characters integers. float. For example. UNIX shells allow you to define variables using data types. and array variables. float. TC shell variables can be either local or global. For example. Korn shell Like the TC shell. This can change the way the shell uses the variables. which are whole numbers floats. You can only declare local variables in the Bash shell. which are floating-point decimal numbers arrays. integer. you can define a variable as an integer or as a character string. and array variables. which are sequences of variables Each of the following popular UNIX shells supports variables and data types in different ways: y y y y Bourne shell Bash shell TC shell Korn shell Bourne shell The Bourne shell supports string variables only.

Korn Shell Targets: A. $ typeset distance=4070 $ If you don't specify a value for a variable in an assignment statement. Supports string variables only Answer The Bourne shell only supports string variables. Using typeset allows you to specify command-line options for the assignment operation. the Bash shell supports string and integer variables. The Korn shell provides good support for variable typing and other useability features. integer. and array variables C. the code assigns the value 4070 to a variable called distance. the shell assigns a null value to the variable. In this example. It's more likely to be deployed on proprietary UNIX systems than on open source systems. . You can assign a value to a variable using the equal sign (=). 2.2. float. Bourne Shell 3. integer. it's useful for writing platform-independent shell scripts. The Bourne shell is the most universally deployed shell and. In this example. Using variables The shell defines variables automatically when you assign a value to them for the first time. and array variables The Bash shell is based on the Bourne shell. Supports string and integer variables B. distance is set to null. they can only be declared locally. Supports string. although it has a limited feature set. float. $ distance=4070 $ You can use the typeset command to assign values to variables. Although you can export variables to make them global. while the Korn shell supports string.

In this example.$ distance= $ To refer to the value of a variable ± rather than to the variable itself ± you precede the variable name with a dollar sign ($). In this example. for example. you use the unset command. the code assigns the value of the distance variable to another variable called temp. In this example. The print statement allows you to confirm that the variable no longer exists. $ unset temp $ print $temp $ Question What do you think is the output of the code shown here? $ t=17h45 $ departure=$t $ print $departure Options: 1. To view the value of a variable. the code removes the temp variable. $ temp=$distance $ To remove a variable entirely. departure . you use the print command and precede the variable name with a $ sign. the code allows you to view the value of the distance variable. t 3. also using the dollar sign. 17h45 2. $ print $distance 4070 $ You can assign the value of one variable to another variable.

The command departure = $t assigns the value of the $t variable to the $departure variable. The value of the $departure variable is set to the value of the $t variable. the shell processes the special characters. the shell displays it without processing the * and & characters. Option 1 is correct. For example. Option 2 is incorrect. $ echo '***** Spain & Portugal *****' ***** Spain & Portugal ***** $ If you omit the quotes. this line of code displays a heading that includes special characters. $ echo ***** Spain & Portugal ***** [1] 55412 ksh: Portugal: not found $ add_pkg_files Spain You can use the following kinds of quotes in UNIX shell scripts: y y y single quotes ('') double quotes ("") back quotes (``) single quotes ('') Single quotes ('') hide the meaning of all special characters. returning a list of files and an error message. you can enclose them in quotes. not the character t. Because the character string is enclosed in quotes. Quoting If you want to prevent the shell from processing spaces and special characters such as & and *.Answer The output of the code is 17h45. This variable is assigned a value of 17h45 in the first line of code. The command print $departure prints the value assigned to the departure variable ± in this case the value of the $t variable set in the first line of code. They allow you to use special characters ± including double and back quotes ± and spaces and newline characters in . 3. It does not interpret $departure as the literal string departure. Option 3 is incorrect.

" $ print $priceline The cost of a trombone is $50. Say you want to define a variable called pricetag and to specify that this variable must contain the string $50. Because the listing needs to be up to date. The Korn shell retains them for compatibility with this shell. you need to use the ls command to obtain it. When you enclose a command in back quotes. the shell executes them and returns the value of their output. You can assign this value to a variable. Using back quotes. Therefore. You need to do this using single quotes to prevent the shell from treating the characters after the $ sign as a variable name. spaces. with the exception of back quotes (``) and the $ and \ characters. Single quotes also prevent variable and command substitution because they hide the meaning of the $ character. double quotes ("") Double quotes ("") hide the meaning of special characters. $ Say you need to declare a variable that contains a full directory listing of the scripts directory. you can assign the output of the ls command to the drlist variable. you can use double quotes to combine variable values with a text string.strings. back quotes (``) Back quotes (``) are a method of command substitution that the Bourne shell uses. $ pricetag='$50' $ item='trombone' $ priceline="The cost of a $item is $pricetag. This means that command and variable substitution still take place in strings enclosed by double quotes. . and newline characters. $ pricetag='$50' $ print $pricetag $50 $ Let's say that you want the shell to read the value of the item and pricetag variables and to include these values in the value of another variable called priceline. You need to use double quotes so that you can combine the variable values with text.

4.$ drlist=`ls -a scripts` $ print $drlist . The backslash escapes all special characters. Question What do you think is the output of the code shown here? $ airline='PA' $ flightno="$airline 771" $ print $flightno Options: 1.. add_pkg_files$ Question In which variable assignment statement is the $ symbol not interpreted as a special character? Options: 1. airline 771 2. including itself. flightno 771 . So the expression \\ will be interpreted by the shell as \. except $. but it does not escape special characters. Option 2 is correct. 3. Option 1 is incorrect. \. Var=&$100 Var=\$100 Var="$100" Var='$100' Answer The backslash and single quotes prevent the $ symbol from being interpreted as a special character. Double quotes prevent most special characters from being interpreted. . Option 4 is correct. 2. Placed at the end of a command. but they can't be nested. Option 3 is incorrect. the ampersand causes the command to run as a background job. and `. Single quotes prevent all special characters from being interpreted.

Some shell environments support more data types than others. Option 3 is correct. You can unset them using the unset command. which is then printed. not the flightno string. Variables and data types | . The print command prints the flightno variable. Back quotes allow you to assign the output of a command to a variable. Option 1 is incorrect. The first command assigns the value PA to the airline variable. so in the command flightno="$airline 771" . you precede the variable name with a dollar sign ($). Summary Variables are named spaces for storing data. Option 4 is incorrect. $airline refers to the variable set in the previous command line. To access the value of a variable.3. Double quotes allow you to create variables that include spaces because everything within the double quotes is interpreted as a single word by the shell. Table of Contents | Top of page | | Learning objective | | 1. The special character $ symbol used to reference variables is retained within double quotes. such as an integer or a character string. and assigns the resulting string to the flightno variable. The second command substitutes the variable at the start of a string that consists of a space and the number 771. You can use quotes when assigning a value to a variable. Option 2 is incorrect. PA 771 4. The value of a variable can be one of several data types. You can set the value of a variable using an assignment statement or the typeset command. Single quotes and double quotes allow you to include special characters in strings. PA771 Answer The output of the code is PA 771 because the double quotes allow variable substitution and the single quotes include the space character.

This allows the shell to process integer values faster. -l) right and left justify (-R. but it prevents you from assigning any non-integer value to the variable. defines a variable as an integer. you should be able to describe and use script variables and parameters. . -F) The float attributes (-E and -F) define a variable as a floating-point decimal number. accessed. and the left justify attribute formats a string variable so that it's left-justified. for example. Quoting | | Summary | Copyright © 2003 SkillSoft. Using variables | | 3. An attribute is a setting that defines how a variable is represented. All rights reserved. or displayed. -F) lowercase and uppercase (-u. -LZ) autoexport (-x) integer (-i) The integer attribute (-i) defines a variable as having the integer data type. -L) right and left justify with zeroes (-RZ.| 2. The integer attribute. All other logos or trademarks are the property of their respective owners. float (-E. Defining variable attributes Any variable can have one or more attributes. | Print | Contents | Close | UNIX shell script variables Learning objective After completing this topic. 1. SkillSoft and the SkillSoft logo are trademarks or registered trademarks of SkillSoft in the United States and certain other countries. The attributes you can set on a variable include y y y y y y integer (-i) float (-E.

-L) The right justify (-R) and left justify (-L) attributes allow you to format data. you use a minus sign (-) to set an attribute and a plus sign (+) to unset it. lowercase and uppercase (-u. $ typeset -i dist $ In this example. whereas variables with the -L attribute display at the left end of the specified field width.1415 and 314. $ typeset +i dist $ . For example.15 both have five digits. For example. right and left justify (-R. you can specify the number of digits in the number. The left justify with zeroes (-LZ) attribute left-justifies a variable to a specified field width and strips all leading zeroes. regardless of the position of the decimal point. 196. autoexport (-x) The autoexport (-x) attribute causes the shell to export a local variable whenever its value is set.160 both have three digits. right and left justify with zeroes (-RZ. the code unsets the integer attribute on the dist variable. you can specify the number of digits after the decimal point. 3. -l) The uppercase attribute (-u) automatically converts any alphabetical characters in a variable's value into uppercase characters. This is useful if you want to ensure that the new value is available throughout the shell. the code sets the integer attribute (-i) on the dist variable. When you use the -F attribute. The lowercase attribute (-l) converts any alphabetical characters in a variable's value into lowercase characters. You need to specify a field width when you set either of these attributes.When you use the -E attribute. -LZ) The right justify with zeroes (-RZ or -Z) attribute right-justifies a variable to a specified field width and fills the remainder of the field with leading zeroes. In this example. Variables with the -R attribute will display at the right end of the specified field width.543 and 2. You use the typeset command to set and unset attributes. Paradoxically.

$ typeset -i dist=489 $ Attributes take precedence over a variable's current value. the code sets the uppercase attribute (-u) and the autoexport attribute (-x) on the name variable. if the value of name is Novak and you set the uppercase attribute (-u) on name. To assign an attribute and a value to a variable at the same time. the code sets the integer attribute (-i) on the dist variable and assigns it the value 489. 4. In this example. In this example. you can't set attributes on a variable that has been unset. After you assign a value to it After you've unset it Before you assign a value to it While you assign a value to it Answer You can set attributes on a variable either before. $ typeset -ux name $ Question At what stage do you think you can set attributes on a variable? Options: 1. 2. . its value becomes NOVAK. However.You can set multiple attributes at the same time. during. you use the typeset command and specify the attribute before the value. $ name=Novak $ typeset -u name $ print $name NOVAK $ You can use the readonly attribute (-r) to prevent any further changes to the value or attributes of a variable. For example. or after assignment. 3.

3. Ensures that the variable contains all lowercase characters B. you cannot unset the readonly attribute on a variable once you've set it. It enables you to make sure that numbers are assigned to the variables. typeset-i typeset -l typeset -L typeset -x Targets: A. Defines the variable as a whole number or its negative Answer The ±i attribute defines a variable as an integer. Options: 1. For example. this command displays a list of all variables with the integer attribute (-i).Unlike other attributes. the ±x attribute exports it. and the ±L attribute ensures that the variable is left justified. the ±l attribute ensures all its characters are lowercase. Ensures that the variable is exported to subshells C. Ensures that the variable is left justified D. The ±i attribute is useful when you are using variables in calculations. 2. $ typeset -i MAILCHECK=600 OPTIND=1 PPID=55394 RANDOM=22348 SECONDS=700 TMOUT=0 dist=489 $ Question Match the variable attribute to its function. You can use the typeset command to display a list of all shell variables that currently have a particular attribute. . rather than letters. 4.

However. including y y y y y y ? The ? parameter contains the exit status of the last command that the shell has executed. the exit status is 0. Examples of environment variables are y y y the SHELL variable. which defines a user's default shell the HOME variable. you will need to add it to a shell configuration file. irrespective of its value. which defines a user's home directory the PATH variable. which defines the search path for commands The shell has some special parameters that allow you to interact with current processes. However if you want the variable to be available between logins.The ±l attribute is useful if you need to format the case of a variable consistently. or to other users. User-defined variables can't use the same names as the environment variables because the system has reserved these names. which is useful when you want to avoid errors in shell scripts in which variables are set interactively by the user.profile file. 2. They are global variables declared in each user's . If it didn't execute successfully. They allow you to control the behavior of the shell or to obtain information about current processes. the exit status is non-zero. If the command executed successfully. users can change the value of environment variables. Environment variables are parameters that control the shell's behavior. If you want to make a variable available to subshells. Working with parameters Parameters are reserved variables that the shell uses. The ±L attribute strips any leading spaces from a variable. ? ! $ PPID ERRNO . you must export it using the ±x attribute.

parameter 1 contains the first argument. Parameter 0 contains the name of the command or function to which the arguments apply. the value of parameter 1 is a. or function. and the value of parameter 2 is the specified directory path. or unset them. for example. 3. 2. the value of parameter 0 is ls. parameter 2 contains the second argument. ERRNO The ERRNO parameter contains the error number returned by the most recent failed system call. Question What do you think you can do to the values of special parameters such as ? and $? Options: 1. They allow you to use these arguments in subsequent lines of a script. $ The $ parameter contains the process ID (PID) of the current shell process. set them. In this command. PPID The PPID parameter contains the process ID (PID) of the current shell's parent shell process. so it may not be available on all systems. and so on. 4. This parameter is system-dependent. ! The ! parameter contains the process ID (PID) of the last background command or coprocess that the shell has executed.parameter contains the shell options that are set on the current shell process. script. Positional parameters contain arguments that have been passed to a command. Reassign them Set them Unset them View them Answer You can view the values of special parameters. but you can't reassign them. Positional parameters are named according to the positions of the arguments they contain.The . .

$ ls -a /usr/home Positional parameters are particularly useful in functions. This example of a function searches the current directory for a specified file and displays the contents of the file one screen at a time. When you call the function and specify a filename as an argument, the filename is stored in the positional parameter $1. This allows the commands in the function to work with the filename. disf() { > ls -al | grep $1 > cat $1 | more > } $ You can call positional parameters only up to $9. If you want to use ten or more positional parameters, you need to enclose the identifying numbers in the parameter names in braces ({}). For example, the tenth positional parameter is ${10}. The expression $* returns the values of all current positional parameters, separated by spaces. The expression $# returns the number of current positional parameters.

Question
Identify the true statements regarding positional parameters. Options: 1. Although commands can take any number of arguments, you can only view nine positional parameters 2. Positional parameter 2 contains the second argument to be passed to a command 3. Positional parameter 0 always contains the value of a command or name of a function 4. You can use positional parameters within a function to manipulate its arguments

Answer
Positional parameter 0 refers to the command or function itself, while parameter 2 refers to the second argument passed to the command. One of the main uses of positional parameters is to call the arguments to a function from within the function.

Option 1 is incorrect. You can view positional parameter 10 or greater, but you must enclose it in braces, as in ${10}. Option 2 is correct. For the command cat file1 file2, the value of $2 is file2. Option 3 is correct. For the command cat file1 file2, the value of $0 is cat. Option 4 is correct. You can access an argument to the special_cat function as shown here: special_cat () {cat $1 | less}

Summary
You can set attributes that apply to a variable. Attributes can modify the way the shell processes a variable ± for example by defining it as an integer or floating-point decimal number. They can also modify the way the shell displays a variable value ± for example by specifying that it display as uppercase or left-justified characters. Parameters are predefined system variables. They include environment variables, which define characteristics of the shell environment, special parameters, which allow you to obtain data about current processes, and positional parameters, which allow you to work with arguments.

Table of Contents
| Top of page | | Learning objective | | 1. Defining variable attributes | | 2. Working with parameters | | Summary |
Copyright © 2003 SkillSoft. All rights reserved. SkillSoft and the SkillSoft logo are trademarks or registered trademarks of SkillSoft in the United States and certain other countries. All other logos or trademarks are the property of their respective owners.

| Print | Contents | Close |

Variable expansion and arrays in UNIX shell scripts
Learning objective

After completing this topic, you should be able to explain variable expansion and use array variables.

1. Variable expansion
Variable expansion allows you to access the values of variables. The simplest form of variable expansion involves referring to the value of a variable directly. To do this, you place a dollar sign ($) in front of a variable name. Other forms of expansion allow you, for example, to refer to portions of a variable's value or to the length of a variable's value, or to specify default or alternative variable values. You can use braces ({}) to delimit the value of a variable from any characters following the variable name. This allows you to use the variable name in assignment statements that change the value of the variable. In this example, the variable en contains the name "EasyNomad." Using braces, you can change its value to "EasyNomadTravel" by invoking its original value. $ en=EasyNomad $ en=${en}Travel $ print $en EasyNomadTravel $ If you precede a variable name with a hash sign (#), you can determine the length of its value ± the number of characters it contains. In this example, the output of the command specifies that the value of the en variable contains 15 characters. $ print ${#en} 15 $ The following variable expansion formats allow you to work with default and alternative values: y y y y y ${variable:-word} ${variable:=word} ${variable:+word} ${variable:?word} ${variable:?}

${variable:-word}

The ${variable:-word} syntax returns the value of the variable if it's set and non-null. If it's not set or if it's set to null, the expression returns the text string word. For example, ${name:-Name not found} returns the value of the name variable. If name is null or not set, it displays the message "Name not found". ${variable:=word} The ${variable:=word} syntax returns the value of the variable if it's set and non-null. If it's not set or if it's set to null, the expression assigns the text string word to the variable and then returns the variable's new value. For example, ${name:=anonymous} returns the value of the name variable. If name is null or not set, it assigns the value "anonymous" to name and returns the value "anonymous". ${variable:+word} The ${variable:+word} syntax returns the text string word if the variable is set and non-null. If it's not set or if it's set to null, the expression returns nothing. For example, ${name:+Name already exists} returns the string "Name already exists" if the value of the name variable is set and non-null. If name is null or not set, nothing is displayed. ${variable:?word} The ${variable:?word} syntax returns the value of the variable if it's set and non-null. If it's not set or if it's set to null, the expression returns the text string word and the shell terminates. You can use this format to ensure that essential variables are set before a script executes further. ${variable:?} The ${variable:?} syntax returns the value of the variable if it's set and non-null. Otherwise, the expression returns the default error message "parameter null or not set" and the shell terminates. The following variable expansion formats allow you to extract substrings from variable values: y y y y y y ${variable:start} ${variable:start:length} ${variable#pattern} ${variable##pattern} ${variable%pattern} ${variable%%pattern}

${variable:start}

It therefore returns "ing ground on island". It then removes this substring and returns the remainder of the value. if the value of the en variable is EasyNomad. ${variable:start:length} The ${variable:start:length} syntax returns part of the value of a variable. beginning at the left of the variable's value. For example. the expression ${en:4} returns "Nomad". It therefore returns "landing ground on is". The expression ${tour#land*} finds the first and shortest instance of land* and removes it. the expression ${tour%*land} finds the last and shortest instance of land* and removes it. ${variable#pattern} The ${variable#pattern} syntax finds the shortest substring that matches pattern. if the value of the tour variable is "landing ground on island". say the value of the tour variable is "landing ground on island". the expression ${tour##land*} finds the first and longest instance of land*. For example. which is the entire string. beginning at the right of the variable's value.The ${variable:start} syntax returns part of the value of a variable. from the character position specified by the integer start to the end of the value. beginning at the right of the variable's value. if the value of the tour variable is " landing ground on island". For example. It then removes this substring and returns the remainder of the value. The selected substring begins at the character position specified by the integer start and contains as many characters as specified by length. ${variable##pattern} The ${variable##pattern} syntax finds the longest substring that matches pattern. ${variable%pattern} The ${variable%pattern} syntax finds the shortest substring that matches pattern. It then removes this substring and returns the remainder of the value. beginning at the left of the variable's value. if the value of the en variable is EasyNomad. For example. ${variable%%pattern} The ${variable%%pattern} syntax finds the longest substring that matches pattern. It removes this and returns nothing. For example. the expression ${en:4:3} returns "Nom". It then removes this substring and returns the remainder of the value. .

say the variable heading contains the string "Last-minute flights and cutprice flights". Question You have set the value of the file variable to file1. . the expression ${heading//flight/tour} returns the string "Last-minute tours and cut-price tours". the expression ${col3#Cost/Price} returns the string "Price of flight". In this case. Removing this. For example. For example. if the variable heading contains the string "Last-minute flights and cut-price flights". The following variable expansion formats allow you to find and replace substrings in variable values: y y y y ${variable/pattern1/pattern2} ${variable//pattern1/pattern2} ${variable#pattern1/pattern2} ${variable%pattern1/pattern2} ${variable/pattern1/pattern2} ${variable/pattern1/pattern2} replaces the first instance of pattern1 in a variable's value with pattern2 and returns the result. For example. which is the entire string. the expression ${heading/flight/tour} returns the string "Last-minute tours and cut-price flights". if the value of the tour variable is "landing ground on island". For example. it returns nothing. say the variable col3 contains the string "Cost of flight. the expression ${col3%flight/cruise} returns the string "Cost of cruise".For example. ${variable//pattern1/pattern2} The ${variable//pattern1/pattern2} syntax replaces all instances of pattern1 in a variable's value with pattern2 and returns the result. the expression ${tour%%*land} finds the last and longest instance of land*." In this case. ${variable%pattern1/pattern2} The ${variable#pattern1/pattern2} syntax replaces the last instance of pattern1 in a variable's value with pattern2 if the value ends with pattern1. ${variable#pattern1/pattern2} The ${variable#pattern1/pattern2} syntax replaces the first instance of pattern1 in a variable's value with pattern2 if the value begins with pattern1. if the variable col3 contains the string "Cost of flight".

4. and return just part of a variable. not the string or integer itself. 3. preceding the variable name with a # symbol returns the number of characters in a variable. 3. return the number of characters in a variable. so only the last character is returned. Question What do you think you can do using variable expansion formats? Options: 1. Option 4 is incorrect. 2. Options: 1. Option 3 is correct. 4. This only happens if the file variable has either not been assigned. 2. extract a substring from the value of a variable. or perform an arithmetic operation on it if it is an integer to create a new value. Option 2 is correct. The command en=${file}2 changes the value of the variable to file12 The command echo ${#file} returns the integer 5 The command echo ${file:4} returns the integer 1 The command echo ${file:?} returns a null value and exits the shell Answer Variable expansion allows you to reuse the current value of a variable when assigning a new value. When using braces to expand a variable. In this case the variable has been assigned a five-character string. you can display a custom error message if a variable is not set. . You can expand the current value of a variable and include it as part of a new string. and replace a substring in the value of a variable with another substring. The number in this syntax identifies where the returned string starts. Option 1 is correct. Display a custom error message if a variable is not set Extract a substring from the value of a variable Replace a substring in the value of a variable with another substring Replace the value of one variable with the value of another variable Answer Using variable expansion formats.Select the statements that correctly describe variable expansion of the file variable. or has been assigned a null value.

that value becomes the value of the array's first element. The name of an array variable denotes the entire array. Therefore. the subscript of the second element is [1]. Arrays Arrays are variables that can contain multiple values. this command will output the message "File not found": echo ${file:-File not found} Option 2 is correct. Question How do you think you create an array variable? Options: 1. the subscript of the first element is [0]. By applying the array attribute to an existing variable By assigning a value to one of its elements By assigning a value to the array By creating an ordinary variable with the typeset command using the array attribute ±A Answer You create an array variable by assigning a value to one of its elements. You simply assign the variable as shown: newvar=$file 2. This subscript takes the form of a number enclosed in square brackets. . 3. you can replace the 1 with a 2 using the command: echo ${file/1/2} Option 4 is incorrect. If the file variable has been assigned the value file1. you can return just the 1 using the command: echo ${file:4} Option 3 is correct. Variable expansion isn't used for this. 2. and so on.Option 1 is correct. If the file variable has been assigned the value file1. Numbering begins at zero. 4. You refer to an individual element in an array using a subscript that identifies its position in the sequence of elements in the array. or has a null value. stored as a sequence of elements. If a variable already has an existing value when you convert it into an array. If the file variable is not set.

In this example. thereby making it an array. In this example. beginning with the subscript n. Assuming that the value of count is 3 and the fourth element in the array is "wooden giraffe". which lists souvenirs for sale. ${!array[*]:n} The ${!array[*]:n} syntax lists all array elements. It then assigns the value "February" to the mth[1] element. the code assigns a value to element 4 + 9 of the items array." $ items[4+9]="safari hat" $ print ${items[$count]} wooden giraffe $ The following variable expansion formats allow you to work with array variables: y y y y y y ${array[*]} ${!array[*]} ${!array[*]:n} ${!array[*]:n:x} ${#array[*]} ${#array[n]} ${array[*]} ${array[*]} lists all elements of an array. the code assigns the value "January" to the mth variable. For example. ${!array[*]:n:x} . The value of mth[0] is still "January. The next line of code displays the element whose subscript is contained in the variable count. ${!items[*]:5} lists all elements of the items array from the sixth element onwards. the resulting output is "wooden giraffe." $ mth=January $ mth[1]=February $ print ${mth[0]} January $ If you use arithmetic expressions or variables in the subscript of an array element. the shell evaluates the expressions or variables and then references the array. ${!array[*]} ${!array[*]} lists all initialized subscript values of an array.

as well as the number and length of this element. $ get_item() { > print "Item no. using the appropriate array variable expansion format. the data for the third element of the items array displays.The ${!array[*]:n:x} syntax lists x array elements. Let's say that you want to write a function that accepts an element number as an argument and displays a specified element. "$1+1 . The items array is an existing array that lists souvenirs for sale. $1" print "Length ${#items[$1]}" print ${items[$1]} } When you call the get_item function for element 2. ${#array[*]} The ${#array[*]} syntax returns the number of elements in an array. seventh. in the items array. You do this using a positional parameter. You decide to name the function get_item. you print the value of the specified element. $ get_item() { > print "Item no. beginning with the subscript n. ${#array[n]} The ${#array[n]} syntax returns the length of the array element specified by the subscript [n]. $ get_item() { > You begin by printing the subscript specified in the argument. $1" > print "Length ${#items[$1]}" Finally. ${!items[*]:5:3} lists the sixth. $1" Then you print the length of the specified element. and eighth elements of the items array. For example. $ > > > > $ get_item() { print "Item no. $ get_item() { > print "Item no.

. the variable var is an array. You use an element's subscript to reference the element.> print "Length "${#items[$1]} > print ${items[$1]} > } $ get_item 2 Item no. The value returned when you use the # metacharacter will be equivalent to the value of the last subscript to be initialized for the array. and ${#var[*]} returns the number of elements in an array. Returns the number of elements in the array Answer The statement ${var[*]} returns all the elements in the array. The * metacharacter is used as a wildcard. 2 Length 14 leopard poster $ Question In this question. Returns all the elements of the array B. ${!var[*]} returns every initialised subscript. Returns all the initialized subscript values of the array C. Match the expansion statements for the var variable to their corresponding functions. Options: 1. A subscript consisting of a number equal to the total number of elements in the array is initialized whenever you add an element. ${#var[*]} Targets: A. ${var[*]} 2. You use the ! metacharacter to reference the subscript values in an array. You use it to reference every element in an array. ${!var[*]} 3.

Using variable expansion formats. Performing simple arithmetic You can incorporate arithmetical and logical expressions in UNIX command-line statements and shell scripts. Arrays | | Summary | Copyright © 2003 SkillSoft. | Print | Contents | Close | UNIX arithmetic operators and precedence Learning objective After completing this topic.Summary The process of variable expansion allows you to work with the values of variables. You assign and access the elements of an array using a subscript in square brackets. All rights reserved. The shell evaluates these expressions and substitutes the results for the expressions themselves. SkillSoft and the SkillSoft logo are trademarks or registered trademarks of SkillSoft in the United States and certain other countries. you should be able to use arithmetic operators in shell scripts. you can simply assign an integer value to it. To declare an integer variable. For example. However. All other logos or trademarks are the property of their respective owners. 1. the code itemID=5 declares the integer variable itemID. . the shell works with positive integers only. You can also provide default and alternative values. Variable expansion | | 2. You can store multiple values in a variable by turning it into an array. you can extract or replace part of a variable's value. Table of Contents | Top of page | | Learning objective | | 1.

you use a hash symbol (#) between the base and the value. To do this. you can also declare an integer variable explicitly. $ i = `expr $i + 1` More recent versions of UNIX support the let command. $ typeset -i itemID=5 Integer variables in the UNIX shell don't need to use the base-10 decimal system. which improves performance and allows type checking. $ integer itemID=5 Alternatively. The let command doesn't require that you use a dollar sign ($) when referring to a variable's value. In this example. To specify a base number other than 10 for an integer variable. although this is the default. This example shows the variable i being incremented by 1. In early versions of UNIX. you can declare variables explicitly using the typeset command with the -i option to set the integer attribute on them.However. $ let i=i+1 If you include spaces or special characters in an arithmetical expression. In this example. which makes it up to 60 times faster than the expr command. you need to enclose it in quotes. $ typeset -i16 position=B1F7 Note You can use any base between 2 and 36. $ nibble=2#1101 You can specify a base number after the -i option of the typeset command. you use the integer command. the code assigns the binary value 1101 to the nibble variable. the expr command was used to evaluate expressions. This bypasses the process of variable expansion. $ let "i=i + 1" . the code assigns the hexadecimal value of B1F7 to the position variable.

2. you can use double brackets as shown here. Multiplication (*) and division (/) operators take precedence over addition (+) and subtraction (-) operators.command to display negative values. ((18%8)) evaluates to 2. $ ((i=i + 1)) When the shell evaluates an arithmetical expression. unless you use brackets to override this precedence. However. For example.As an alternative to using the let command to evaluate expressions. 4. . you need to use the print . leaving a remainder of 2. which returns the remainder that results from the division of one expression by another. The UNIX shell supports a modulo operator (%). 36 72 120 144 Answer The expression 12 * (48 / 6 + 2) evaluates to 120. $ ((rem = 18 % 8)) $ print $rem 4 $ You can assign negative values to variables by placing a minus sign (-) immediately in front of the value. because 18 divided by 8 is 2. The shell treats the code in the brackets as an arithmetical expression and evaluates it. it follows the conventional order of precedence for arithmetical operators. Question What do you think is the result value of the following expression? 12 * (48 / 6 + 2) Options: 1. because otherwise the print command interprets the minus sign in a variable value as an argument. 3.

$num -9 $ Question Identify the true statements concerning declaring integer variables. Logical and bitwise operations The UNIX shell supports logical operators that perform Boolean logic operations on expressions. You can make a variable an integer variable by simply assigning it an integer value. such as variables containing binary numbers. Option 4 is incorrect. Binary numbers are base 2. and you can use variables with base 2 integers as values. 3. Options: 1. To explicitly declare an integer variable. 4. Option 1 is correct. Option 3 is correct. although the default is 10. which are base 2. 2. You can declare hexadecimal integers like this: Variable=16#b6 Option 2 is correct. Integer variables can use any base between 2 and 36. The logical operators that the shell supports are y y y logical AND (&&) logical OR (||) logical negation (!) .$ let "num = -9" $ print . You can declare integers that aren't base 10 You can use binary numbers as integers You use the typeset option to explicitly declare an integer variable You need to explicitly declare integer variables Answer You can use the typeset option to explicitly declare integer variables that aren't base 10. you use the typeset ± i option. 2.

It returns a 0 only if both bits are 0. The UNIX shell supports several bitwise operators. bitwise XOR (^) . ((2#1101 & 2#1001)) evaluates to 2#1001. logical OR (||) The || operator compares two expressions logically and evaluates the entire expression to zero if either of them are true. the entire expression evaluates to one.logical AND (&&) The && operator compares two expressions logically. logical negation (!) The ! operator evaluates an expression and then reverses it logically. The bitwise operators are y y y y bitwise AND (&) bitwise OR (|) bitwise XOR (^) bitwise negation (~) bitwise AND (&) The & operator compares two expressions bit by bit. For example. If either of the bits is 1. the ! operator changes it to one. it returns a 1. Whereas logical operators compare and manipulate entire expressions. If either or both are false or evaluate to one. This is chiefly useful for working with binary numbers. ((2#1101 | 2#1001)) evaluates to 2#1101. It returns a 0 if either of the bits is 0. and vice versa. If an expression evaluates to zero. The entire expression evaluates to one only if both expressions are false. it returns a 1. If both bits are 1. If both are true or evaluate to zero. For example. bitwise operators perform Boolean logic on individual bits. bitwise OR (|) The | operator compares two expressions bit by bit. the entire expression evaluates to zero.

. If one of the bits is a 1 and the other is a 0. The UNIX shell supports bit shift operators. For example. shifting their bits either to the left or to the right by a specified number of places. ((~ 2#1001)) evaluates to 2#110. For example. it returns a 1. Question Which operator performs bitwise reverses on the value of each bit in a binary expression? Options: 1. These act on binary number values. 4. 3. bitwise negation (~) The ~ operator acts on one expression to turn all zeros into ones and vice versa. ~ & ^ | Answer The ~ operator performs bitwise negation on the value of each bit in a binary expression. 2. The right shift operator (>>) shifts bits to the right. Bits at the right end of the original values are lost. If you perform bitwise negation on the base2 integer 10001. ((2#1001 << 1)) evaluates to 2#10010 and ((2#11 << 2)) evaluates to 2#1100. For example.The ^ operator compares two expressions bit by bit. ((2#1101 ^ 2#1001)) evaluates to 2#100. The left shift operator (<<) shifts bits to the left. The newly created bits on the right are zeros. Option 1 is correct. the result will be 1110. For example. ((2#1001 >> 1)) evaluates to 2#100. It returns a 0 if both bits are 1 or if both bits are 0.

3. The first statement compares the two binary numbers. You use the | symbol to perform a bitwise OR on two binary expressions. 2. Where both bits are set. You use the ^ symbol to perform a bitwise XOR on two binary expressions. Option 3 is incorrect. This would be the result if the first statement were a bitwise OR. unsetting set bits and setting unset bits. the leading zero would be stripped. This would be the result if the first statement were a bitwise XOR. yielding a result of 1011. bit by bit. 4. This is not valid output for a binary integer. The first statement sets x to 2#0100 and the second statement performs bitwise negation on this value. Option 3 is incorrect. 0100 11 0 100 Answer The output of this code is 2#1011. If it were. Where one bit isn't.$y Options: 1. the returned bit is also set. Option 4 is incorrect. You use the & symbol to perform a bitwise AND on two binary expressions. Additional operators . Option 1 is incorrect. The second statement performs bitwise negation.Option 2 is incorrect. Option 4 is incorrect. the returned bit is also not set. yielding a result of 1111. 3. Question What do you think is the output of the following piece of code? ((x = 2#1101 & 2#110)) ((y = ~x)) print . Option 2 is correct.

it returns a 1 (false). ((count+=1)) increments the count variable by 1.The UNIX shell supports a range of comparative operators that compare the values of two expressions. The comparative operators that the UNIX shell supports are y y y y y y less than (<) greater than(>) less than or equal to (<=) greater than or equal to (>=) equal to (==) not equal to (!=) less than (<) The < operator returns 0 (true) if the expression before it evaluates to a lower value than the expression after it. Otherwise. Otherwise. The UNIX shell simplifies this task with increment and decrement operators. . These are useful when you need to set conditions for conditional statements. greater than(>) The > operator returns 0 (true) if the expression before it evaluates to a higher value than the expression after it. it returns a 1 (false). less than or equal to (<=) The <= operator returns 1 (false) if the expression before it evaluates to a higher value than the expression after it. greater than or equal to (>=) The >= operator returns 1 (false) if the expression before it evaluates to a lower value than the expression after it. One of the most common arithmetic tasks consists of incrementing or decrementing a variable. The increment operator (+=) sets a variable to a new value that's equal to its previous value plus any number you specify after the operator. Otherwise. Otherwise. Otherwise. it returns a 0 (true). not equal to (!=) The != operator returns 1 (false) if the expression before it evaluates to the same value as the expression after it. it returns a0 (true). it returns a 1 (false). it returns a 0 (true). equal to (==) The == operator returns 0 (true) if the expression before it evaluates to the same value as the expression after it. For example. If not.

so the value that is assigned to $x is 1. Question You have issued the following command to assign values to variables: x=4 . The next expression increments the value of $x by 2. When a conditional expression evaluates as false. The decrement operator (-=) sets a variable to a new value that's equal to its previous value minus any number you specify after the operator. y=2 Which statements will not yield an error to this command? Options: . and the print statement prints the new value of $x ± 3 ± to the screen. So the value of $x that is incremented by 2 is 1. 2 3. Option 3 is correct. respectively. 419 2. 3 Answer The output from this code is 3. The $? variable is assigned the exit status of the previous command. and when $x is printed it has a value of 3. The first line evaluates a conditional expression and returns a value of 0 or 1. The first line does not return a value of 417. Option 1 is incorrect. For example. the previous command is the conditional expression that evaluates as false. ((remainder-=1)) decrements the remainder variable by 1.Question What do you think is the output of the following piece of code? ((417 <= 28)) x=$? ((x += 2)) echo $x Options: 1. Option 2 is incorrect. In this case. depending upon whether the expression evaluates as true or false. a value of 1 is returned.

subtraction. so the statement is correct. $x >= $y. The == operators means "is equal to". Summary You can evaluate arithmetical expressions using the let command or the ((«)) construct. 2. $x >= $y $x < $y+=4 $x == $y $x != $y Answer $x < $y+=4.1. and modulo operators. so this statement would result in an error. The basic arithmetical operators include addition. making it larger than the x variable. The +=4 operator increments the y variable by 4. Performing simple arithmetic | | 2. Option 4 is correct. The UNIX shell supports logical and bitwise operators that perform Boolean logic on entire expressions or on individual bits of binary numbers. Option 3 is incorrect. so this statement is correct. The != operator means "is not equal to". These follow the conventional precedence order ± with multiplication and division taking precedence over addition and subtraction ± unless parentheses override this convention. The UNIX shell also supports comparative operators that compare the values of two expressions. multiplication. 3. 4. and $x != $y all use comparative and increment operators correctly to construct valid statements. Logical and bitwise operations | . division. The x variable is greater than variable y. Table of Contents | Top of page | | Learning objective | | 1. Option 2 is correct. Option 1 is correct. The >= operator means that the value on the left is equal to or greater than the value on the right of the operator.

All rights reserved. All other logos or trademarks are the property of their respective owners. This involves the following tasks: y y creating and assigning variables performing arithmetical calculations Let's say that you're working for the EasyNomad travel company and you're required to write a script that calculates the amount of commission that agents earn on each package tour they sell. you're required to write a piece of code that performs calculations using variables. #!/usr/local/bin/ksh MISSING CODE . Type the command that declares variables explicitly and the attribute that specifies a variable to be an integer. SkillSoft and the SkillSoft logo are trademarks or registered trademarks of SkillSoft in the United States and certain other countries. Additional operators | | Summary | Copyright © 2003 SkillSoft. you need a variable to store the commission percentage that agents receive and another variable to store the amount received. Step 1 of 2 The commission percentage will be stored as a positive integer. Exercise overview In this exercise. | Print | Contents | Close | Using calculations in a UNIX script Learning objective After completing this learning object. you should be able to use variables and arithmetic in a shell script. Task 1: Assigning variables For the commission script.| 3.

Result The typeset -i command declares integer variables explicitly. You repeat the same task to create the amount variable. Step 2 of 3 . You don't assign a value to amount yet because it still needs to be calculated. Step 1 of 3 Type the command that evaluates arithmetical expressions. #!/usr/local/bin/ksh typeset -i MISSING CODE Result You type commrate=10 to create and set the variable. #!/usr/local/bin/ksh typeset -i commrate=10 typeset -i amount Task 2: Performing calculations The script you are writing needs to accept the value of a tour package that an agent sells as its first argument. Complete the line of code that creates a variable called commrate and assigns the value of 10 to it. #!/usr/local/bin/ksh typeset -i commrate=10 typeset -i amount MISSING CODE Result The let command evaluates arithmetical expressions. Step 2 of 2 Let's say that agents receive a commission of 10 percent.

#!/usr/local/bin/ksh typeset -i commrate=10 typeset -i amount let amount=$1 let amount=amount*commrate/100 print amount Table of Contents | Top of page | | Learning objective | | Exercise overview | . You add a print statement to output the value of the amount variable. Step 3 of 3 Type the arithmetical expression that applies the commission percentage to the value of the amount variable.Type the code that assigns the value of the script's first argument to the amount variable. #!/usr/local/bin/ksh typeset -i commrate=10 typeset -i amount let amount=$1 let amount= MISSING CODE Result You type amount*commrate/100 to apply the commission percentage to the value of the amount variable. #!/usr/local/bin/ksh typeset -i commrate=10 typeset -i amount let MISSING CODE Result You type amount=$1 to assign the value of the script's first argument to the amount variable. The script is now complete.

All other logos or trademarks are the property of their respective owners. The text editors at this time were referred to as line editors because they required all changes to a file to be made on a line-by-line basis. Text formatters allow you to specify features such as fonts.| Task 1: Assigning variables | | Task 2: Performing calculations | Copyright © 2003 SkillSoft. maintain. margins. you need a separate program to format it. Early text processing One of the original purposes of UNIX was to develop. It was later rewritten in C. SkillSoft and the SkillSoft logo are trademarks or registered trademarks of SkillSoft in the United States and certain other countries. and footnotes when displaying or printing documents. although it retained the same functionality. and track documents and memos in the AT&T/Bell Telephone Company in the late 1960s. . Each command to a line editor specified a line number. and the changes to be applied to that line. You can run this formatter using the command roff. | Print | Contents | UNIX text tools Abstract This article discusses the history of UNIX text and format processing tools. All rights reserved. The original standard UNIX linemode text editor ± named "ed" ± was first compiled in assembly language. binary output is not legible to human beings. Output needs to be in plain text for processed data to be accessible to both the computer and its human operator. paragraphs. Plain text Although computer processors act on binary data. Text formatting To improve the readability of text created in a text editor on UNIX systems ± and to print this text. next runoff (nroff) and typesetting runoff (troff) have been developed to provide additional features and greater flexibility. Since runoff. The earliest UNIX text formatter was runoff. which was named after print runs in the publishing industry. spacing.

and bibliography macros. and tables. The most commonly used tools are y y y the sed utility the awk language the PERL language sed . It is especially suited to material with a high mathematical content. you receive a UNIX prompt inside the current Emacs window. This allows you to navigate through the document to edit pieces of text at random. as well as support for indexing. it provides Greek symbols. TeX provides fonts and font sizes. Digital Standard Runoff (DSR). Shell programming tools In addition to the runoff text formatter. You can start up a UNIX shell from inside Emacs. TeX and LaTeX TeX is a text processor used mainly in scientific and mathematical environments to produce papers. At the core of Emacs. and alternative character sets. For example.Other text formatters such as SCRIPT for IBM mainframes. Emacs The Emacs text editor was written mostly in the programming language Lisp. It provides automated section and chapter. Emacs is a visual editor in that it displays a representation of an entire document on screen. mathematical equations. Scribe. You can also open more than one document at a time and use Emacs windows to move between documents. line drawing. diacriticals. books. footnotes. diagrams and boxes. and TeX. This built-in programming language allows you to customize and extend Emacs. there are a number of text tools that system administrators commonly use in shell programming. and TeX have also been developed. multicolumn printing. there is a full-featured Lisp interpreter written in C. cross-referencing. mathematical characters. LaTeX is a set of macros based on TeX macros that facilitates the structuring of large documents. In this case. and theses. page layout. You can then run commands ± including compile commands ± as you would outside of Emacs and save the shell output to a file. Emacs.

You can run awk commands from the command line as a simple text-processing tool. Summary Developed to support a documentation project in the AT&T/Bell Telephone Company. the awk command will remove the second field from each line in a file called profile. This allows you to delete lines of text by "replacing" them with nothing. . process. sed.The sed utility is a stream editor that allows you to search for and replace text strings in a file. it is most commonly used as a UNIX command-line filter to reformat the output of other commands. such as PERL commands. to format text. or to extract information for other programs. In the following example. awk is a complete patternscanning and processing language. and grep as built-in functions. runoff was subsequently developed to improve the readability of printed documents. Because the early line editors lacked textformatting capability. Weinberger.print} profile PERL PERL (Practical Extraction and Report Language) is a portable text. Its syntax resembles the syntax you use in shell programs and in C programming. the sed command deletes the first two lines of the easynomad. PERL was developed originally as a data reduction language capable of processing large quantities of data efficiently. Aho. In the following example. However. or you can create a command file containing awk statements. You can execute sed commands at the command line or you can run a command file to replace characters and strings in a specified data file.*one/s/line/LINE/' -e '/line/d' easynomad. and filemanipulation tool that bridges the gap between shell and C programming. It allows you to extract parts of a large body of text. ed was the first text editor for UNIX text files. awk {$2="". which is especially useful in the case of lengthy system logs and e-mails.txt awk Named after its originators.txt file: sed -e '/^line. PERL also includes awk. and Kernighan.

sed. It processes one line of standard input at a time and returns the results as standard output. sed is a noninteractive line editor. SkillSoft and the SkillSoft logo are trademarks or registered trademarks of SkillSoft PLC in the United States and certain other countries. process.More comprehensive text-processing tools such as TeX ± which is used in scientific environments ± and Emacs ± which is used for programming ± were developed to improve on the runoff tool. and PERL. . 1. Awk allows you to perform pattern-scanning and processing. sed allows you to perform search and replace operations. Table of Contents | Top of page | | Abstract | | Plain text | | Early text processing | | Text formatting | | TeX and LaTeX | | Emacs | | Shell programming tools | | Summary | Copyright © 2003 SkillSoft PLC. you should be able to explain how to use the sed line editor. All other logos or trademarks are the property of their respective owners. All rights reserved. and PERL is a text. Introducing sed Unlike text editors that allow you to alter a file by moving the cursor on the screen. | Print | Contents | Close | UNIX editing with sed Learning objective After completing this topic. and file-manipulation tool. The three most commonly used text-processing tools are awk.

you can also use it to append. You can perform many of these functions using the vi text editor. and to perform substitutions on all or specific lines. As a result. Question Because sed works with open format files ± or plain text files ± it is portable and supports a wide range of text applications. What do you think you can use sed for? Options: 1. Converting double and triple spacing in a file Converting DOS newlines to UNIX newlines Deleting leading or trailing spaces and consecutive blank lines Performing substitutions on all or specific lines Sorting information in a text file Answer You can use sed to convert line spacing in a file and to convert DOS newlines to UNIX newlines. 4. You can execute sed operations by y y using the -f flag creating a sed executable file using the -f flag . Sed applies each editing command to the first line in a file and then moves on to subsequent lines one at a time. display. It doesn't alter original files. However. an entire file is never loaded into memory. 2.In most cases. However. You can also use sed to delete leading or trailing spaces and consecutive blank lines. In its simplest operation. 5. delete. sed works as a filter that searches for a specified pattern and takes a specified action if it matches the pattern. 3. You often use sed to perform search and replace operations on the content of specified text files. or insert text. sed provides a better solution than the vi text editor for working with multiple text files. it processes input via a keyboard and returns output to the screen.

sed reports. . but in this example it just contains sed commands.sed | sed reports.sed Option 2 is correct.sed.txt | sed ±f edit. Which sed command do you execute at the command line to edit the file reports. The file containing the sed commands is provided after the ±f option. Option 4 is incorrect. you would use the following command: cat reports.sed reports.txt sed ±f reports.txt edit. This command would work if edits. 4./edit.txt Answer You use sed ±f edit. but to do so. However. which you can then pass as a file for execution by sed using the -f option. 2. You use the ±f option to specify the file containing the sed commands.txt causes sed to execute the commands in a file called sample.sed were an executable file. 3. and not after the file on which sed is to operate on.sed. Question You have stored sed editing commands in a text file named edit. you need to use the chmod command to give the file execute permissions before you can run it.txt to edit the reports./ command.sed memo. creating a sed executable file An executable sed script contains the line #!/usr/bin/sed -f.sed . the code sed -f sample. cat edit.txt file using the sed commands in edit. which allows you to run it through the shell using the . Option 3 is incorrect.sed on a file called memo.You can create a script containing only editing commands.txt. and then you provide one or more files for sed to operate on.txt? Options: 1. For example. It is possible to pipe input into sed.txt sed ±f edit.sed reports. Option 1 is incorrect.

^ $ * ? [ ] . Matching expressions with sed To specify a sed command in a script or on the command line. for example. it denotes the first line in a file. the command sed 's/^Thu /Thursday/' easynomad will substitute Thu with Thursday only when Thu occurs at the beginning of a line. $ The $ expression attempts to match a pattern string with the end of a line in a specified file. If a ^ replaces a line number. you follow the command with a string that includes the following components: y y y editing command regular expression and pattern string replacement text For instance. For instance. the command sed 's/ $//' easynomad will replace any space character ( indicated by a forward slash ( that occurs at the end of a line. the command sed 's/[ ]*//' easynomad will delete any spaces in the file. Note The sed utility supports most of the regular expressions that other UNIX text utilities ( such as awk. * The * expression attempts to match any occurrences of a specified character with characters in the content of a specified file. and grep ( and UNIX shells support. For instance. gawk. For instance.2. The most commonly used regular expressions with the sed command are y y y y y ^ The ^ expression attempts to match a pattern string with the beginning of a line in a specified file. the code sed 's/^night/day/' substitutes the word "night" with the word "day" when the word night occurs at the beginning of a line.

The -s option to sed substitutes anything matched by the first expression with the contents of the second expression. In this case. sed 's/[ ][^ ]*$//' test2 3. the command sed 's/?D/4/' easynomad will substitute the first instance of the letter D with the number 4. See if you can match each sed command with the function it performs." Question Sed allows you to use combinations of regular expressions. For instance. For instance. sed 's/ *$//' test1 2. Options: 1. Finds all blank lines by identifying each line end that follows immediately after a line beginning C. [ ] The [ ] expression attempts to match the content of the square brackets with a specified pattern string. and sed 's/^$/ blank line/' test3 finds all blank lines by identifying each line end that follows immediately after a line beginning. sed 's/^$//' test3 Targets: A. sed 's/[ ][^ ]*$//' test2 deletes the last word on each line. Deletes all trailing spaces from each line B. The $ matches the end of a . Deletes the last word on each line Answer The command sed 's/ *$//' test1 deletes all trailing spaces from each line. the metacharacter * matches the preceding character ± a space ± zero or more times.? The ? expression attempts to match one instance of a specified character with the content of a specified file. the command sed 's/[Ee]asy[Nn]omad/EasyNomad/g' easynomad will substitute uppercase and lowercase instances of the letters "e" and "n" with the word "EasyNomad.

the circumflex (^) matches the start of a line or string. You can preface sed commands with line numbers to specify which lines in the input file are to be modified by the sed command. In this example.you would adapt the expression as follows: sed 's/^$/---/' test3 In addition to the substitute command (s). When it is not preceding a class or range. but testing requires an s (substitution) command to change the current line before control is passed. append (a). control passes to the end of the script. The expression [. To insert a paragraph separator such as --. Note The UNIX man pages provide a full listing of the sed options. . but which contains anything other than a space thereafter. If you wanted the string inserted before line 9. with examples of their usage.txt. you can use the insert (i). ^$ matches the start and end of an empty line. For instance. If the label does not appear in the script.][^ ]*$ matches any string that starts with a space. Branching passes control to the end of the script automatically. the effect is to delete all trailing spaces from each line. The effect of this is to match every word at the end of a line. The -s option to sed substitutes anything matched by the first expression with the contents of the second expression. 2 s/tourist/tourists/ looks for the string "tourist" in line 2 of a specified file and replaces it with the string "tourists. and is at the end of a line. and delete (d) commands with the sed command. Because nothing is specified in the second expression. You can use two advanced sed commands ± branching (-b) and testing (-t) ± to rearrange the order in which portions of a script execute.txt deletes the last line in a file named text. For instance. These commands transfer control to a line containing a specified label. you would specify the command sed 9 i\Copyright EasyNomad 2003. the sed command appends the string "Copyright EasyNomad 2003" after line 9 in a specified file.line." In the example sed 9 a\Copyright EasyNomad 2003. the command sed '$d' text.

4. Question Match the sed regular expression characters with their descriptions. For example. You can precede your sed command with the number of the line on which it is to operate. 3. You use the a command to append text in sed. You preface sed commands with the specific line on which you want them to operate. Matches a class of characters . 2. You use the ±n option to suppress printing of all output except that explicitly matched by the sed command. Options: 1. Options: 1. 3. Option 2 is correct.Question Identify the true statements regarding sed commands. You use the i command to insert text in sed. this command adds the text "circa 1848" to the start of line 10: sed 2 i\circa 1848 Option 4 is incorrect. this command adds the text "circa 1848" to the end of line 10: sed 2 a\circa 1848 Option 3 is correct. 4. while the i command inserts it. You can specify the line on which a sed command will operate You use the a command to append text in sed You use the i command to insert text in sed You use the ±n option to insert new lines Answer The a command appends text to the specified location. 2. For example. ^ $ * [ ] Targets: A. Option 1 is correct.

Matches the end of a line Answer You match the start of a line with ^ and the end of a line with $. Matches the beginning of a line D.with (100) so that you can distinguish the area codes from the rest of phone numbers more easily.B. this command changes DOS newlines to the UNIX format: sed 's/.com Tanya (100) 555-2222 100-555-1113 TanyaS@easynomad.com Sam 101-555-1111 101-555-2222 SamO@easynomad. zero or more times. zero or more times. The ^ command matches the beginning of a line. Matches any number of the preceding character C. You use [ ] to match a class of characters and * to match the preceding character. The output shows that only the first instances of "100-" in each line were changed.05a$ sed 's/100-/(100) /' phonelist. The following sed command will replace the character 2 with 1: sed 's/2*/1/g' The [ ] command matches a class of characters. To do this.$//' The * command matches the preceding character. For example.txt Name Home_Number Cell_Number E-Mail Greg (100) 100-555-1111 100-555-1112 GregL@easynomad.com . you enter the code shown here. bash -2. Editing text with sed Let's say that you have a simple phone list that you need to extract data from using sed commands. Suppose that you begin by replacing instances of 100. For example. the following sed command will delete any line that starts with a number: sed '/^[1-9]/d' 3. In this example. the sed command will delete any new line that starts with a space: sed '/^ /d' You match the end of a line with the $ command.com Daniel (100)555-3333 101-555-1114 DanielB@easynomad.

05a$ sed 's/100-/(100) /g' phonelist.05a$ sed 's/2222/5555/p' phonelist. The command to change "100-" to "(100)" . Using the p option prints Tanya and Sam's records because these are the only records that contained the string "2222".txt Name Home_Number Cell_Number E-Mail Greg 100-100-555-1111 100-555-1112 GregL@easynomad. .com Tanya (100) 555-2222 (100) 555-1113 TanyaS@easynomad.$d/' phonelist. bash -2.com bash -2.Nick (100)555-4444 101-555-1115 NicholasN@easynomad.05a$ To change all instances of "100-" in each row. For instance. for instance.com Sam 101-555-1111 101-555-5555 SamO@easynomad.com Daniel (100) 555-3333 101-555-1114 DanielB@easynomad.com Sam 101-555-1111 101-555-2222 SamO@easynomad. both Greg and Tanya's cell numbers are now prefixed with "(100)". bash -2.com bash -2.05a$ You can use the q (quit) option to display lines up to and including a specified line ± line 5.05a$ sed 's/4.com Nick (100) 555-4444 101-555-1115 NicholasN@easynomad. its original content doesn't change.txt Name Home_Number Cell_Number E-Mail Greg (100) 100-555-1111 (100) 555-1112 GregL@easynomad.com Tanya 100-555-2222 100-555-1113 TanyaS@easynomad. changes only the data output and not the original text. in this example.com bash -2. Let's say that you want to replace the string "2222" with "5555" and to instruct sed to print only the lines affected by the change.txt Name Home_Number Cell_Number E-Mail Tanya 100-555-5555 100-555-1113 TanyaS@easynomad. you use the g option. bash -2.com bash -2.05a$ The example here shows how you can use the d (delete) option to display a specific number of lines ± in this case. the first three lines ( in a file.05a$ Note Even though you've used s (substitution) options on the phone list file.

05a$ Let's say that you want to print all records in the phone list except Sam's record.com Sam 101-55-1111 101-55-2222 SamO@easynomad.com Daniel 100. In this example.txt Name Home_Number Cell_Number E-Mail Greg 100-100-555-1111 100-555-1112 GregL@easynomad.bash -2. bash -2.05a$ sed 's/555/55/g' > newphone.05a$ sed 's/^Sam/d' phonelist.com Daniel 100-555-3333 101-555-1114 DanielB@easynomad.05a$ You can direct the output of a sed command to a new file.com Tanya 100-555-2222 100-555-1113 TanyaS@easynomad. it's advisable to write a script that you can then run against the file. bash -2.com Tanya 100-555-2222 100-555-1113 TanyaS@easynomad.com bash -2. cat sedscript s/555/55/g s/100-/(100) /g s/101-/(101) /g s/easynomad/EasyNomad/g .555-1112 GregL@easynomad.txt. To do this.com bash -2.txt Name Home_Number Cell_Number E-Mail Greg 100-100-55-1111 100-55-1112 GregL@easynomad.555-3333 101-555-1114 DanielB@easynomad. In this example.com Tanya 100-55-2222 100-55-1113 TanyaS@easynomad.05a$ If you want to execute a number of sed commands on the same text file. the script contains a number of s (substitution) commands.com Nick 100-55-4444 101-55-1115 NicholasN@easynomad.com bash -2.txt Name Home_Number Cell_Number E-Mail Greg 100-100-555-1111 100.com Nick 100-555-4444 101-555-1115 NicholasN@easynomad.05a$ sed '5q' phonelist. the code replaces a 3-digit string with a 2-digit string and saves the output in a new text file named newphone. you use the d (delete) option with the specification that all lines beginning with the word "Sam" be excluded from the output.com Daniel 100-55-3333 101-55-1114 DanielB@easynomad.com Nick 100-555-4444 101-555-1115 NicholasN@easynomad.

When you run a sed script against the phone list text file, it outputs the table with all the substitutions in the script implemented. bash -2.05a$ sed -f sedscript phonelist.txt Name Home_Number Cell_Number E-Mail Greg (100) 55-1111 (100) 55-1112 GregL@EasyNomad.com Tanya (100) 55-2222 (100) 55-1113 TanyaS@ EasyNomad.com Sam 101-55-1111 (101) 55-2222 SamO@ EasyNomad.com Daniel (100) 55-3333 (101) 55-1114 DanielB@ EasyNomad.com Nick (100) 55-4444 (101) 55-1115 NicholasN@ EasyNomad.com bash -2.05a$

Summary
Sed is a noninteractive line editor, which processes one line of standard input at a time and returns the results as standard output. To specify a sed command in a script or on the command line, you follow the command with regular expressions, the pattern string that you want the command to locate, and replacement text for this string. Sed allows you to perform a range of text edits on plain text files, either as single or multiple command-line instructions or by passing multiple instructions in a script.

Table of Contents
| Top of page | | Learning objective | | 1. Introducing sed | | 2. Matching expressions with sed | | 3. Editing text with sed | | Summary |
Copyright © 2003 SkillSoft. All rights reserved. SkillSoft and the SkillSoft logo are trademarks or registered trademarks of SkillSoft in the United States and certain other countries. All other logos or trademarks are the property of their respective owners.

| Print | Contents | Close |

Creating a configuration script

Learning objective

After completing this topic, you should be able to use sed in a UNIX shell script to edit a file.

Exercise overview
In this exercise, you're required to create a new configuration file and perform a sed substitution. This involves the following tasks: y y redirecting sed output substituting a text string

Task 1: Redirecting sed output
Let's say that you want to adapt the configuration file named "hosts" on the primary GLEESON server for use on the secondary server, without changing the original file. You decide to use sed to search and replace host addresses and to save the output as a new file called "en_hosts".

Step 1 of 2
Let's say that you want to change all instances of "190" to "192". See if you can type the sed command that will substitute the 190 string.

sed MISSING CODE

Result
You enter 's/190/192/g' to specify the global substitution that will change all instances of "190" to "192."

Step 2 of 2
Let's say that you want to create a new configuration file containing the changed output. Choose the code that you think will specify hosts as the input file and en_hosts as the output file.

$ sed 's/190/192/g' MISSING CODE Options: 1. en_hosts > hosts 2. hosts > en_hosts 3. en_hosts < hosts

Result
The code that specifies hosts as the input file and en_hosts as the output file is hosts > en_hosts Option 1 is incorrect. This option uses en_hosts as the input file and hosts as the output file. Option 2 is correct. The data on the left of the > redirector is written to the file on the right of the redirector. Option 3 is incorrect. This command would redirect the hosts file as an argument to the command on the left of the redirector. Since en_hosts is a file, this command will generate an error.

Task 2: Substituting a text string
Step 1 of 2
Let's say that you need to change all instances of "gleeson" to "gleeson_assoc" in the en_hosts configuration file. Choose the code that you think will substitute all the text strings that match "gleeson."

$ sed MISSING CODE Options: 1. 2. 3. 4. 's/^gleeson/gleeson_assoc/g' 's/gleeson_assoc/gleeson/g' 's/gleeson/gleeson_assoc/p' 's/gleeson/gleeson_assoc/g'

Result

You enter 's/gleeson/gleeson_assoc/g' to specify the substitution that will change all instances of "gleeson" to "gleeson_assoc" in the en_hosts configuration file. Option 1 is incorrect. This would only replace the string "gleeson" if it appeared at the start of a line. Option 2 is incorrect. This would replace gleeson_assoc with gleeson, instead of vice versa. Option 3 is incorrect. The g flag is required to ensure the each instance is replaced, not just the first. The p flag sends the results of each replacement to standard output. Option 4 is correct. You use the s command with the g flag to perform global substitutions. The first term is the search term that is replaced with the second term.

Step 2 of 2
See if you can complete the sed command to output the new configuration information to screen.

$ sed 's/gleeson/gleeson_assoc/g' MISSING CODE

Result
You enter en_hosts to specify the filename of the new configuration file.

Table of Contents
| Top of page | | Learning objective | | Exercise overview | | Task 1: Redirecting sed output | | Task 2: Substituting a text string |
Copyright © 2003 SkillSoft. All rights reserved. SkillSoft and the SkillSoft logo are trademarks or registered trademarks of SkillSoft in the United States and certain other countries. All other logos or trademarks are the property of their respective owners.

| Print | Contents | Close |

Programming with awk for UNIX

Introducing awk Like the sed line editor. 2. 4. 3. including data extraction. loops. 1. Which of the following operations do you think awk allows you to perform on a text file? Options: 1. Note Awk derives its name from the surnames of its developers. However.Learning objective After completing this topic. such as conditionals. you need to specify y y the input data the awk program or script the input data . you should be able to explain how to use awk. and generate formatted reports. use variables to manipulate the text as if it were data in a database. Question Awk uses common programming constructs. Awk allows you to perform a variety of data processing tasks. and Kernighan. analysis. its extensive programming syntax classifies it as a programming language rather than as a simple text utility. awk scans and processes patterns in a text file. Viewing a text file as a table of records and fields Using variables to manipulate the text as if it were data in a database Generating formatted reports Performing search and replace operations Answer Awk allows you to view text files as tables of records and fields. and reporting. Weinberger. Aho. To use the awk command. and arithmetic and string operators.

This is an alternative to using the -f option to specify the name of a program file. Question . You can also provide standard input by piping another program or UNIX command into awk. you can specify options with the awk command using the following syntax: y y y y -f program file program source -F character -v var=value -f program file You can use the -f option with the name of a program file to specify the file containing the awk program code to execute. When you enter the program source on the command line. you need to enclose the code in single quotes to prevent it from being interpreted as shell code. -F character You use the -F character option to set the field separator in the input data to a character other than the default white space. the awk program or script The awk script specifies how the input data is to be processed. You can specify this data as one or more files or you can use standard input from the keyboard after executing the awk command. This sets the specified variable prior to execution. -v var=value You use the -v var=value option to initialize a variable on the command line.The input data is the data that awk is to process. You can specify the awk script as a file passed with the awk command or you can specify it on the command line. program source You can enter the program source ± the code that the awk program needs to execute against ± on the command line. This is an alternative to entering the required source code on the command line. you enter -F:. For instance. to set the field separator that the input data uses to a colon. In addition to the input data and the awk script.

Awk only operates on a single data file per command You can enter the program code for awk on the command line You can initialize variables from the awk command line You use the ±f option to specify a file containing awk program code Answer Awk program code can be entered on the command line or you can use the ±f option to read it from a file. When awk encounters any occurrence of that pattern within a line. You can specify multiple files for an awk program to use as input. it will select the line. . You can initialize variables used by awk from the command line. 4. the code fragment deposit = $5 instructs awk to use the value in column 5 for calculations involving the deposit. 3. you can use a matching operator such as the equals (=) sign. 2. Options: 1. you can store the program instructions in a text file to read in from the awk command line. Awk building blocks Awk works by matching a specified pattern with data in an input file and taking a specified action on all lines that contain pattern matches. To specify an awk command. Option 1 is incorrect. Option 2 is correct. 2. To select records on the basis of data in a particular field. If you have a complex awk program that you want to reuse. awk [-v var=value] [-F field separator] [--] 'pattern {action}' var=value datafile(s) You enclose the actions that awk must perform in braces ({}) so that awk can differentiate them from their associated patterns. You can specify the patterns to be matched and the actions to be taken as a single awk command line statement. A string of characters placed between forward slashes (//) is called a regular expression.Identify the statements that correctly describe the use of awk. Option 4 is correct. Option 3 is correct. You can use the ±v option on the awk command line to name a variable used in your awk code and assign it an initial value. you use the following basic syntax. For instance.

END is called after awk has finished processing the last file. and less than or equal to (<=). Rather. The END statement allows you to specify actions ± such as printing an ending text line or calculating cumulative variables such as line counts or column totals ± that need to occur after awk has processed the last input line. you can search for patterns using relational expressions such as greater than (>). The BEGIN statement is called once only before awk reads any data lines. you can specify awk variables only when they're needed. } . For instance. The BEGIN statement allows you to specify actions ± such as resetting variables or creating column headings for output ± that need to occur before awk starts processing input lines.05a$ bash: / : is a directory bash-2. bash-2. And you can address both regular and relational expressions in compound forms using the logical OR (||) and logical AND (&&) operators. If the source program for awk includes multiple files.In addition to regular expressions in an awk command. The END statement is called after awk has read and processed all lines.05a for i in terry larry mary do mail $i << END $(date) Have a good holiday $i! END quit exit clear { en='EasyNomad' print en. less than (<). You don't need to specify awk variables before you use them. this code prints the string "EasyNomad" to screen.

For instance. length. Awk allows you store sets of values in associative arrays. which you can use in awk scripts to return values needed by the script. whereas the $0 expression represents the number of the current record as a single variable. These arrays are known as associative arrays because you can reference the values they include using a string or an index number. FS and OFS The FS and OFS variables represent the input field separator and the output field separator respectively. NF or the $1-$n syntax Both the NF variable and the $1-$n syntax denote the number of fields in the current record. y These are divided into arithmetic functions ± such as cos. You can change some of these variables ± such as the default field separator. int. By default. log. you can write a function that returns values sorted in a specified order. A value with its index number is known as an element. Awk updates other reserved program variables ± such as current record number ± automatically. The most commonly used reserved program variables are y y y y NR or $0 NF or the $1-$n syntax FS and OFS RS and ORS NR or $0 The NR variable denotes the number of the current record. which means that awk interprets each line in an input file as a separate record. Awk allows you to define your own functions for use in multiple scripts by using the function command to specify a list of statements. sin. . Awk provides a number of functions. and rand ± and string functions ± such as index. exp. It also appends a newline character to the end of each record that it sends to standard output.Awk provides reserved program variables. RS and ORS The RS and ORS variables represent the input record separator and the output record separator respectively. both separators are newline characters. and match.

2. the $0 positional parameter references a command itself. Question Which statements accurately describe awk syntax? Options: 1. it acquires a different meaning in the syntax of the awk command interpreter.You use this syntax to create an array. The first argument to the awk command The first field in a line of input An entire line of input A null variable Answer The $0 expression is an awk field variable that matches an entire line of input. the END statement is called after each is processed . 3. In the syntax of the shell command interpreter. array[index] = value You can use a special for structure with an awk array to loop through the array elements. what does the $0 expression denote? Options: 1. The first field in a line of input is referred to with the $1 field descriptor. Option 1 is incorrect. all variables have a null value until a value is assigned to them. Option 2 is incorrect. However. but you can use the ±F option to define the field delimiter. 4. Option 4 is incorrect. using this syntax. for(elem)action Question In terms of awk syntax. The $0 field descriptor matches every field in a line of input. If multiple files are called. The default field delimiter is a space. Option 3 is correct. In awk.

You don't want the lines to wrap. Let's say that you want to print a text file to a screen that is limited to a width of 80 characters per line. Option 2 is incorrect. you want to check whether there are any lines in the file that exceed 80 characters. You can use awk to reformat text files awk for improved readability or for export into other applications. . awk variables can be initialized as you need them. For instance. As is generally true of shell scripting. Option 1 is incorrect. The code awk '/#/ {print "Comment found "}' /etc/hosts will print "Comment found" for each line that contains at least one hash sign anywhere in the line. You can use the BEGIN statement to perform initial operations. 3. Once all input has been processed.2. such as creating columns or assigning values to variable. you use the code awk 'length > 80' hosts. Option 4 is correct. where they are located in the file. before processing any input. you may want to know whether a configuration file contains comments ± indicated by a hash sign (#) ± and. the END statement is called only once. Irrespective of the number of files on which the awk code operates. while the END statement specifies actions taken after processing all input. Option 3 is correct. You use the BEGIN statement to specify actions that take place before processing any input 4. You use the END statement to specify actions that are performed after input is processed Answer The BEGIN statement specifies actions to be taken before processing all input. after all the input has been processed. You must declare any variables used in your awk program on the command line 3. Before entering complex formatting instructions. if so. To do this. Programming with awk One of the main uses of awk is to find out about the content of a text file. you can use actions defined in the END statement to manipulate the processed data.

txt changes the single line spacing in the file nomad.txt to double-line spacing in a file named nomad1. You use single quotes in this way to hide special characters from the shell. :)" Options: 1.txt. In the code. and increments it by one. for example. In this example. Question Awk allows you to perform integer and floating point mathematical operations on input files. the code awk '{print . . A printout of all blank lines in a file } Answer The code will calculate the number of blank lines in a file and return the result to the screen. Option 1 is correct. The number of non-blank lines in a file 3.For instance. the awk program initialises the x variable with a value of 0. Awk can process text that has been broken into multiple logical fields. Each time a blank line is detected. The code awk -F":" '{ print $1 }' /etc/passwd. And you can reference individual fields in an awk script.txt > nomad1. print ""}' nomad. When awk processes the print $1 command. accompanied by the text strings enclosed in double quotes. prints a list of all user accounts on the local system. The number of blank lines in a file 2. The print command sends the value of x to standard output. the -F option changes the field separators between multiple fields in the passwd file from the default spaces to colons. the single quotes allow the use of double quotes in the awk expression. it will print out the first field that appears on each line in the input file. What do you think the output of the following script will be? BEGIN { x=0 } /^$/ { x=x+1 } END { print "I found " x " blank lines.

The pattern that is matched ± in this case blank lines ± is not automatically printed. For instance. Table of Contents | Top of page | | Learning objective | | 1. analysis. $1/$2}' > text2. Introducing awk | | 2. Awk works by matching a specified pattern with data in an input file and taking a specified action when it locates this pattern. All rights reserved. Awk building blocks | | 3. One of the main uses of awk is to find out about or change the content of a text file. you can use it to determine whether a file includes comments or to reformat a file for improved readability. Programming with awk | | Summary | Copyright © 2003 SkillSoft. You can use awk with other UNIX commands.Option 2 is incorrect. All other logos or trademarks are the property of their respective owners. | Print | Contents | Close | . The output of the command will be stored in a new file named text2. The regular expression that increments the x variable . Summary Awk allows you to perform a variety of data processing tasks. the content of the text1 file is piped to awk for pattern matching. and reporting. Option 3 is incorrect. including data extraction. such as cat and grep. not lines containing characters. SkillSoft and the SkillSoft logo are trademarks or registered trademarks of SkillSoft in the United States and certain other countries. In the example cat text1 | awk '$1 < $2 {print $0.^$ matches every blank line. The print command only prints the value of the x variable and some helpful text.

Programming with the shell The shell is an interface between the user and a UNIX operating system. They manage the initialization and shutting down of essential system services during system startups and shutdowns. 1. such as transferring files using the File Transfer Protocol (FTP) and then e-mailing users once the files have been downloaded. you should be able to explain the principles of logical flow in a shell program. You can create shell scripts ± consisting of ASCII text files ± that the shell interprets and the operating system executes. . Shell programming is useful for y y y automating tasks prototyping system administration automating tasks A shell program ± or script ± allows you to specify operations in a certain sequence. you can rewrite it in languages such as C++ and Java to improve its performance and extend its functionality. system administration Shell scripts run at system bootup to restore system configurations and to set up services. You can use shell scripting to automate tasks that need to be performed in sequence. as well as the transition from one run-level to another.UNIX shell programming principles Learning objective After completing this topic. You can combine these functions with UNIX command-line programs. Once you've prototyped an application. The shell supports a set of functions implemented as keywords that provide a simple programming language. prototyping You can use shell programming to prototype complex applications so as to provide proof-ofconcept implementations and to test logical functions.

C++. and manipulating graphics or GUIs. or Java. as well as to automate repetitive tasks. For which of the following purposes do you think a compiled language is more appropriate than shell scripting? Options: 1. Scripting tasks that are performed repeatedly Answer Automation involves scripting repetitive tasks. 4. designing proprietary applications. and optimization of shell scripts used to initialize a system is an important part of system administration. 5. Options: 1. . you should use compiled languages such as C. Developing a proof-of-concept application B. Question In certain cases. Question Match the action to the example. 2. developing proof of concept applications is an example of prototyping. Prototyping 3. Optimization of system initilization scripts C. 3. Automation 2. Creating applications with cross-platform portability Designing proprietary applications Improving system performance Manipulating graphics or GUIs Prototyping an application Answer You should use more powerful scripting languages than shell scripting for improving system performance. rather than shell scripting. System Administration Targets: A.System administrators can write shell scripts to analyze the behavior of a system and to modify it.

General programming principles that make it easier to write and interpret programs include y y y writing pseudocode debugging during code construction indenting code for readability writing pseudocode To identify the steps that a program needs to include. if every project you work on has a similar directory structure. Programming fundamentals Programming effectively requires that you first determine the solution that a program must provide. 2. indenting an if then fi statement or a do while loop makes it easier to verify that you've completed the required code correctly so that subsequent code will execute. so understanding shell programming techniques is essential to optimizing your system. you should use pseudocode. You then plan the components that the program requires to do this and determine how the components will fit together to execute the required tasks. debugging during code construction You should debug a program as you work on it ± rather than after completing it ± to verify that each logical section of code works correctly. together with the programming language components required to achieve the specified tasks. For example. Pseudocode consists of an informal written plan that describes what each item of code must do. you can automate the process of generating the directories for a particular project. Because shell programs are relatively simple to write. it's often useful to test procedures in the shell before incorporating them into programs written in more sophisticated languages. indenting code for readability You should enter spaces between commands and indent code to make it more readable. Ensuring that each section of code works correctly before you continue programming simplifies the debugging process because it allows you to isolate incorrect code more easily.Repetitive tasks can be automated by shell scripts. Core tools available in most programming languages ± including shell scripting ± include . Services and system configurations on UNIX systems are usually initialized by shell scripts. For instance.

Information is passed to functions in the form of arguments. A function can perform operations based on the arguments passed to it. You use if then else statements to check a condition and then to perform an action based on whether the condition evaluates to true or false. functions Functions ± also known as procedures or subroutines ± consist of code that implements a program that you can embed and reuse in a shell script. the then statement executes. If the condition specified in the if statement in this example evaluates to true. and return values for use in the code from which the function is called. the else statement executes to repeat the request that the user enter a valid number. They allow programmers to create modular code that is easier to maintain and extend than code implemented as a single routine. If the if statement evaluates to false. In the example shown here.y y y y conditional statements functions loops variables conditional statements You use conditional statements to control the flow of statement execution in a program. The following code is shown on screen: echo "Please enter a value less than 10:" read VALUE check_value () while [ $VALUE ±gt 10 ] do echo "Please enter a value less than 10:" read VALUE done echo "The value you have chosen is $VALUE" } check_value VALUE loops . the check_value function ensures that a variable set from standard input corresponds to an appropriate range of values.

2. This is useful for maintaining modularity in complex programs. Debug programs once you've completed the code Indent code and use whitespace to improve readability Use functions to create modular code Use pseudocode to plan programs Answer . When naming a variable. the code will print "Hello World" while the count is smaller than or equal to 5. Question Identify the statements that describe sound programming practice. If the user enters a value of 5. Options: 1. you should ensure that the name isn't used by a function. You should choose a descriptive name. You can use the local keyword in a function to define a variable that is available only to that function. 4. The following code is shown on screen: echo "Enter a number" read NUM COUNT=1 while [ $COUNT -le $NUM ] do print "Hello World" COUNT=$((COUNT+1)) done variables Variables associate a name with a location in memory that contains data. 3. Modern shells ± such as the Korn and Bash shells ± provide for the use of variables with both a local and global scope in shell scripts. You can also use a loop to test a condition and repeat the process until the condition returns an exit status of 1 to indicate that it is no longer true. the loop will print "Hello World" the number of times that the user specifies. for example. In this statement.You use loops to count through a list and to apply a certain action to each element in that list. You can use the name to access and change the data. And a useful convention for shell scripts is to capitalize variable names.

Question Why would you write pseudocode? Options: 1. Summary The shell allows users to interact directly with a UNIX operating system. Pseudocode is not interpreted. it is difficult to accomplish complicated programming tasks without first breaking them down into steps. and . Option 3 is incorrect. and to use functions to create modular code. Option 2 is correct. Option 4 is correct. creating prototype programs. To identify the logical steps in a program 3. you should debug code as you write it. To make your code more readable Answer Pseudocode helps you identify the logical steps needed in your program. so it doesn't affect the readability of your code.It is good practice to plan your programs in psuedocode. Pseudocode isn't included in your actual program. You can use shell scripts to instruct the shell to perform operations in a specific sequence. conditional statements. and thereby improving efficiency. Although pseudocode isn't needed for simple tasks. Shell programming is useful for automating tasks. Option 1 is incorrect. To reduce errors and save time and effort. loops. Option 2 is correct. To assist with debugging procedures 2. it makes debugging and maintenance considerably easier. Creating modular code through the use of functions makes your code easier to maintain and reuse. and simplifying system administration. Option 1 is incorrect. The core tools for programming include variables. Option 3 is correct. Although use of whitespace and indenting is not a functional requirement. to use whitespace to improve the legibility of your code. Psuedocode is particularly useful for organizing your approach to complex programming tasks. so it can't be debugged.

you should be able to use conditional expressions to provide flow control in shell programs. Programming fundamentals | | Summary | Copyright © 2003 SkillSoft. The shell provides a number of tools for testing conditions that simplify the process of building conditional execution into shell scripts. For instance. Programming with the shell | | 2. What do you think are uses of conditional expressions? .functions. General programming principles that you should follow include writing pseudocode. it is a good idea to check that the file exists before executing code that tries to append data to the file. debugging a program as you construct it. 1. | Print | Contents | Close | Testing conditions in the UNIX shell Learning objective After completing this topic. Table of Contents | Top of page | | Learning objective | | 1. All other logos or trademarks are the property of their respective owners. Question You perform tests by evaluating conditional expressions. Testing conditions Programmers frequently need to make the execution of their code dependent on certain circumstances being met. SkillSoft and the SkillSoft logo are trademarks or registered trademarks of SkillSoft in the United States and certain other countries. All rights reserved. and indenting code for readability. if your code needs to append data to a file.

and test file attributes. expression is the condition that you are testing. it will return a syntax error. you can test whether x is less than or equal to y using the following statements: [[ $x le $y]] [ $x le $y ] test $x le $y Compound expressions combine two or more expressions using the y y double ampersand operator (&&). You can test conditional expressions using three different forms of syntax: y y y [ expression ] test expression [[ expression ]] In the syntax. 4. where && means "and" double pipe operator (||).Options: 1. You must include a space between the expression and the brackets. 3. when you compare two variables using the test and [ « ] commands and one of the variables is set to null or is unset. you're less likely to need to resort to quoting. For instance. For example. Determining specific outcomes Evaluating and comparing integers Evaluating and comparing strings Testing file attributes Answer You can use conditional expressions to evaluate and compare integers. evaluate and compare strings. the command will return an exit status of 0 if the conditional expression is true and an exit status of 1 if it is false. When testing an expression. because wildcard expansion and word splitting aren't automatically applied to expressions in the [[ « ]] command. Furthermore. 2. where | | means "or" . The [[ « ]] command is preferable to the test and [ « ] commands because it helps avoid syntax errors.

The ±n option to the test command returns a value of 1 if the variable being tested has a null value 3. The following string operators are useful for checking that variables used in a program have been assigned appropriate values: y y y -n ± true if length of string is not zero -o ± true if option is set -z ± true if length of string is zero The following code fragment executes the set_var function until the $VAR variable is assigned a value that is not null. The [[ condition ]] syntax is backwardly compatible with the Bourne shell Answer . In this case. a student's class mark has to be higher than the average mark of the class and higher than 80. [[ expression1 && expression2 ]] Suppose that you want to ensure that two conditions are met before printing a message. You can use conditional operators within a test command 4. set_var (){ echo "Enter a variable" read VAR } while [[ -z $VAR ]] do set_var done Question Identify the statements regarding the test command that are true. $[[ $class_mark > $class_average && $class_mark > 80 ]] \ && print "Your class mark is very high" You can use the [[ « ]] syntax together with string operators to test variables. Options: 1. Spaces on either side of the [ symbol are not interpreted by the shell 2. you can combine two expressions using the syntax shown here.For example.

You can use the && operator to require two conditions to be met. Conditional expressions can form part of conditions evaluated by the test command. Option 2 is correct. but not by the Bourne shell. 2. Option 1 is incorrect. so if you neglect to include white spaces on either side the shell will return a syntax error. Option 3 is correct.If test ±n returns a 1 when testing a variable. The shell returns a value of 1 when a condition evaluates as false. The ±n option is used to test that a a variable has been assigned a non-null value. Conditional statements You can compare one string with another string using the syntax [[ string1 = string2 ]]. then that variable has a null value. For example." [[ $DESTINATION = "Belize" ]] && print "flights available" You can use the following string operators to compare strings: y y y y = You use the [[ string = pattern ]] syntax shown here to test if a string matches a pattern constructed using a combination of literals. and you use the || operator to require only one of two conditions to be met. Option 4 is incorrect. prints the message "flights available. this code tests whether the string "Belize" has been assigned to the $DESTINATION variable and if it has. The [ and ] symbols are commands. The [[ condition ]] syntax is supported by the Korn shell. the format options to the date command assign values such as "Saturday" and = != < > . Consider the following code: DOTW=$(date +%A) [[ $DOTW = S* ]] && echo "Weekend!" In this case.

The syntax returns a true value if the string fails to match the specified pattern. the string "abc" is smaller than "bcd" and so the code echoes the string "Smaller." You use the following options ( in the syntax [[ option filename ]] ( to test files: y y y -a ( to test whether a file exists -d ( to test whether a file is a directory -f ( to test whether a file is a regular file . The DOTW variable is then tested to see whether it starts with an "S". Consider the following code: DOTW=$(date +%A) [[ $DOTW != S* ]] && echo "Workday!" In this example."Wednesday" to the DOTW variable. the string "bcd" is greater than the string "abc"." > You use the [[ string1 > string2 ]] syntax to test if the characters in string1 comes after characters in string 2 in the dictionary. Consider the following code: SMALLER=$(abc) [[ $SMALLER < bcd ]] && echo "Smaller" In this code. the string "Workday!" is echoed. < You use the [[ string1 < string2 ]] syntax to test if the characters in string1 comes before characters in string2 in the dictionary. and if it does. so the code echoes the string "Bigger. and if it doesn't. the string "Weekend!" is echoed. the DOTW variable is tested to see whether it does not start with an "S". != You use the [[string! = pattern ]] syntax to test if a string doesn't match a pattern. The string operators test the lexigraphical order of two strings. Consider the following code: BIGGER=$(bcd) [[ $BIGGER > abc ]] && echo "Bigger" In this example. A string that appears before a second string in the dictionary is considered "smaller" than the second string.

-L The [[ -L filename ]] syntax returns an exit status of 0 if the specified file exists and is a symbolic link. [[ -s new ]] && print "The file contains data" Additional file options that the Korn shell provides for testing file attributes include y y y y -G The [[ -G filename ]] command returns an exit status of 0 if the specified file exists and the group ID of the file matches the effective group ID for the current process. Sockets are file descriptors and obey file descriptor semantics. -O The [[ -O filename ]] syntax returns an exit status of 0if the user ID for the specified file matches the effective user ID for the current process. Symbolic links can bridge file systems and link to directories. you can compare files using the following syntax: y y y [[ filename1 -ef filename2 ]] [[ filename1 -nt filename2 ]] [[ filename1 -ot filename2 ]] -G -L -O -S [[ filename1 -ef filename2 ]] The expression [[ filename1 -ef filename2 ]] evaluates whether two files are the same. . -S The [[ -S filename ]] syntax returns an exit status of 0 if the specified file exists and is a socket.y y y y y -r ( to test whether a file is readable -w ( to test whether a file is writable -x ( to test whether a file is executable -s ( to test whether a file contains any data -u ( to test whether a file has a user ID bit set for it To test whether a file named "new" contains data so that you don't overwrite it if it does. A symbolic link is a directory or file name that you use to change to another directory without typing its full pathname. you use this statement. for example. In addition to using options to test file attributes.

[[ filename1 -nt filename2 ]] The syntax [[ filename1 -nt filename2 ]] checks if filename1 is newer than filename2. 2. for example. backupfile -nt currentfile currentfile -ef backupfile currentfile -ot backupfile currentfile -nt backupfile Answer You use the statement [[ currentfile -nt backupfile ]] && print "Overwriting older file" to ensure that the program will overwrite only files older than the backup version of the file. To return an appropriate message to users who enter an age of 64. You want to back up a file named "currentfile" and to ensure that the program only overwrites files by this name that are older than the backup version to ensure that the information it contains remains up to date. [[ filename1 -ot filename2 ]] The syntax [[ filename1 -ot filename2 ]] checks if filename1 is older than filename2. you use the following integer operators: y y y y y -eq You use the -eq option with the syntax [[ expr1 -eq expr2 ]] to test whether expression1 is equal to expression2. What statement do you think you need to use to ensure that only older files are overwritten? [[ MISSING CODE ]] && print "Overwriting older file" Options: 1. To compare expressions involving integers. you use -eq -ne -le -ge -gt . 4. Question Suppose that you're writing a program that backs up files. 3.

for example. [[ $age ±ne 64 ]] && print " Your age is 64" -ne You use the -ne option with the syntax [[ expr1 -ne expr2 ]] to test whether expression1 is not equal to expression2. . [[ $age ±ge 64 ]] && print " Your age is above 64" You use this code to return an appropriate message to users who enter an age equal to or above 64. you use this code. -le You use the -le option with the syntax [[ expr1 -le expr2 ]] to test whether expression1 is less than or equal to expression2. See if you can identify the command that you think will do this. [[ $age ±le 64 ]] && print " Your age is below 65" -ge You use the -ge option with the syntax [[ expr1 -ge expr2 ]] to test whether expression1 is greater than or equal to expression2.this code. [[ $age ±ne 64 ]] && print " Your age is not equal to 64" You use this code to return an appropriate message to users who enter an age other than 64. for example. for example. [[ $age ±gt 64 ]] && print " Your age is above 64" Question Suppose that you want to test if a file named "travel" exists. To return an appropriate message to users who enter an age greater than 64. To return an appropriate message to users who enter an age at or below 64. for example. -gt You use the -gt option with the syntax [[ expr1 -gt expr2 ]] to test whether expression1 is greater than expression2. you use this code.

The Bash shell supports the following arithmetic test options: -lt ± less than . Question Suppose that if the file named "travel" exists. See if you can identify the code required to do this. Read more about conditional testing using the Bash shell. and are slightly more versatile.#!/usr/local/bin/ksh if MISSING CODE then Answer You use the statement [[ -a travel ]] to check if the file named "travel" exists. you want to test that it contains data. #!/usr/local/bin/ksh if [[ -a travel ]] then print "The file if MISSING CODE then print "The else print fi else print "The file fi exists" file is not empty" "The file is empty" doesn't exist" Answer You type [[ -s travel ]] to check that the file contains data. Footnote The Bash shell supports the use of single and double square brackets ([] and [[]]) for conditional testing. Double square brackets are a recently added feature.

the test shown here will evaluate as true. Options: 1. Option 1 is correct. This operator will return a value of 1 if the two strings have different values. 4. Option 4 is incorrect. If variables X and Y have different values. Option 3 is incorrect. This operator will return a value of 0 if the string on the right of the operator has a greater value than the string on the left of the operator. Question Match the options in the syntax to the description of their function. != = > < Answer The != string operator will cause a test condition to return a value of 0 if the strings being compared are not the same. as represented by a return value of 0: [[ $X != $Y ]] Option 2 is incorrect. This operator will return a value of 0 if the string on the left of the operator has a greater value than the string on the right of the operator.-le ± less than or equal to -eq ± equal to -ge ± greater than or equal to -gt ± greater than -ne ± not equal to Question Which operator will return a 0 if you compare two strings with different values? Options: 1. 2. [[ -a filename ]] . 3.

files. This syntax tests whether a file exists C. A test using the ±a option on a filename will evaluate as true if the file exists.2. A test using the ±s option will evaluate as true if the file is not empty. integers. The [[ « ]] command is preferable because it results in fewer syntax errors. All rights reserved. [[ -s filename ]] 3. [[ -x filename ]] Targets: A. This allows you to manipulate files. and the ±x option tests that the file is executable. Testing conditions | | 2. A test using the ±x option will evaluate as true if an executable permission has been set on the file. the ±s option tests whether the file contains data. Conditional statements | | Summary | Copyright © 2003 SkillSoft. check file attributes and do arithmetic tests with the Korn shell. You can compare strings. This syntax tests whether a file is executable Answer The ±a option tests a file's existence. SkillSoft and the SkillSoft logo are trademarks or registered trademarks . test. and the [[ « ]] commands to test conditional statements. or expressions by using the double ampersand (&&) or the double pipe (||) operators. This syntax tests whether a file contains any data B. and strings. You can use compound expressions to test conditions that require the comparison of files. Table of Contents | Top of page | | Learning objective | | 1. and expressions for specific conditions. You can use the [ « ]. Summary The Korn shell allows you to test strings. strings.

| Print | Contents | Close | Using UNIX shell control structures Learning objective After completing this topic. You use the if then command to execute subsequent commands when a given condition is true. if condition then commands fi This code. #!/usr/local/bin/ksh echo "Enter password" read password if [[ $password = password01 ]] then print "You can proceed" fi The if then else command allows you to specify that one set of commands must execute if the condition is true and that another set of commands must execute if the condition is false. If it is. you should be able to use flow control commands in shell programs. All other logos or trademarks are the property of their respective owners. You use the if then command with this syntax.of SkillSoft in the United States and certain other countries. You use the if then else command with this syntax. . the conditional statement evaluates to true and the subsequent code executes to display the message "You can proceed". 1. for example. checks that the password that a user enters is "password01". the if then else command. the if then elif command. Conditional statements include statements that use the if then command. Flow control You use conditional statements to control the flow of code execution in UNIX shell scripts. and the case command.

the statements that follow the else keyword execute. It executes a set of commands if the first condition is true and another set of commands if a subsequent condition is true.if condition then commands else commands fi In this example. If no condition evaluates to true. the statements after the then keyword will execute if the condition for the if command evaluates to true. #!/usr/local/bin/ksh echo "Enter password" read password if [[ $password = password01 ]] then print "You can proceed" else print "Goodbye" exit fi The if then elif command allows you to specify more than one condition. The program will then proceed once the correct password is typed. If the condition is false ± because a user enters a password other than "password01" ± the statements after the else keyword will execute to display the message "Goodbye" and to exit. if condition1 then commands elif condition2 then commands elif condition then commands else commands fi In the example. . the elif command allows you to ask the user to re-enter a password if they typed it incorrectly.

.. the commands associated with the patterns will execute.. patternn) command command. If the single value matches one or more specified patterns. esac This Korn shell script illustrates the use of a simple case statement. pattern2) command command. password01 ) print "User rights are assigned" . it prints a suitable message to standard output. read01 ) print "Read rights only" . echo "Enter password" read password case $password in admin01 ) print "Administrator rights are assigned" ... If the user input for the variable conforms to one of three options. esac Question . the code performs the specified action. In this case. The following code prompts the user to supply a value for a variable called password..#!/usr/local/bin/ksh echo "Enter password" read password if [[ $password = password01 ]] then print "You can proceed" elif [[! $password = password01 ]] then print "Please retype password" read password if [[ $password = password01 ]] then print "You can proceed" else print "Goodbye" exit fi print "Welcome $USER" The case command can compare a single value to a number of other values. case value in pattern1) command command.

/customers to create another menu item that will execute the program named "customers".. esac Answer You type case $menu in to complete the case command that allows the user to type a number to execute a program./flights . 2 ) ./flights . MISSING CODE esac Answer You type 4 ) ./bookings . 3 ) .Suppose that you are writing a menu program that will load a certain program when the user enters a specific number. Question Suppose that you want to add another menu item to run a new program named "customers".. See if you can complete the code that allows the user to type a number to execute a program.../travelpackage .. #!/usr/local/bin/ksh echo "Enter menu number" read menu MISSING CODE 1 ) ./travelpackage . #!/usr/local/bin/ksh echo "Enter menu number" read menu 1 ) . 2 ) .. 3 ) ./bookings . Question . See if you can type the code that adds this program as number 4 to the menu program.

You use loops to perform various tasks in a sequence and to automate system administration. in which case they continue to execute indefinitely. Option 3 is incorrect. This statement is used to execute code based on whether one or more patterns match a particular value. and "airplane. 2." The commands execute after the do statement and the done statement ends the loop. for variable in word1 word 2 « wordn do . if then fi if then else fi if then elif fi case esac Answer To specify the execution of code based on whether a single condition is true or false. and after else if it isn't. 2. A word is a piece of a line that the shell has broken up. Loops can be infinite. Option 1 is incorrect. Introducing and using loops Loops are recursive code that executes repeatedly until a specific condition is met. Option 2 is correct. you use an if then else fi statement. such as "a".Which conditional statement allows you to execute one set of commands if a condition is true. and another if it is false? Options: 1. This statement executes code after then if the specified condition is met. Option 4 is incorrect. This process is called iterative execution. so you need to be careful when specifying conditions. 3. You use the for command with this syntax to execute commands a specific number of times. This statement is useful if you need to use additional conditions after the elif syntax. "apple". 4. This statement only executes code if a condition evaluates as true.

. while condition1 do commands done . as in this code. which you can use to make one or more files executable./mkexe filename1 filename2 « filenamen A loop that uses the while command continues to execute until a specified condition is true. #!/usr/local/bin/ksh integer loopnum=1 for x in a b c do print "Loop $loopnum: x=$x" (( loopnum+=1 )) done This is the output of the script. Loop 1: x=a Loop 2: x=b Loop 3: x=c You can assign parameters to a loop dynamically.commands done For example./mkexe sample To make one or more files that you own executable. you can use this program to display a loop number and a loop value for each iteration of the loop. you use the syntax shown here. #!/usr/local/bin/ksh for FILE do chmod 700 $FILE print "$FILE is executable" done If you save a file named "exe" and you have a script named "sample" then you can make the sample file executable by typing the command .

until condition1 do commands done Question Suppose that you want to debug a Korn shell script that another person wrote. the commands continue to execute until condition1 returns a zero exit status. Syntax errors are usually fairly easy to detect. to create directories using the while command you use the code shown here. Tracking the value of variables is an important part of debugging a script. What do you think the output of this script will be? #!/usr/local/bin/ksh integer y=3 while (( y < 5 )) do print "The value of y is $y" (( y = y + 1 )) done Options: . For example.If the exit status of the conditional statement is zero the commands between do and done are executed. In other words. but logical errors may require monitoring how a variable changes during the course of a script's execution. #!/usr/local/bin/ksh echo "What is the name of the directory" read directory echo "How many directories do you want to make?" read dirnumber count = 1 while [[ $count -le $dirnumber ]] do mkdir $directory$count (( count+=1 )) done A loop that uses the until command continues to execute while a specified condition continues to evaluate to false.

Only two iterations of the loop take place. before incrementing it. The statement that prints the value of y is executed before y is incremented. Option 4 is incorrect.1. Option 2 is correct. The shell checks the logic of loops to prevent code being executed an infinite number of times 2. The first iteration of the loop prints the current value of y. so the first iteration of the loop prints the initial value of y. or a specified number of times 3. The value of y is 3 The value of y is 4 The value of y is 5 4. The second iteration prints the new value. The value of y is 4 Answer The initial value of y is 3 and the loop executes until the value of y is less than 5. Loops execute code while a specified condition is met. You use the test command with the while loop Answer . 4. The output is then as follows: The value of y is 3 The value of y is 4 Option 1 is incorrect. The value of y is 2 The value of y is 3 The value of y is 4 2. Option 3 is incorrect. because after the second iteration the condition on which the loop takes place is no longer true. and then increments it by 1. The value of y is 3 The value of y is 4 3. the first line of code assigns a value of 3 to y. Although y having a value of 2 meets the conditions of the test on which the loops is performed. You must specify the number of parameters that you intend to pass to a for loop 4. which is 3. Question Which statements correctly describe the characteristics of loops? Options: 1.

All rights reserved. These include statements that use the if then command. You can dynamically assign parameters to the for loop. will cause a while loop to execute. the loop will be infinite. or until a condition is met. you can use command-line arguments to assign them. If the condition isn't met. Option 1 is incorrect. you use conditional statements. Flow control | | 2. Option 3 is incorrect. You supply parameters to the for loop on which code is executed. You use the test command with the while loop. | Print | Contents | Close | Using flow control in a UNIX shell program . All other logos or trademarks are the property of their respective owners. so you should take care when specifying conditions on which they take place. and you specify a condtion for which while loops take place. either while or until a specific condition is met or for a specified number of iterations. Summary To control the flow of execution in UNIX shell scripts. Option 4 is correct. Table of Contents | Top of page | | Learning objective | | 1. and the case command. You can use the test command to specify a condition. Option 2 is correct. Loops can be infinite. the if then else command. A loop is a set of commands that executes ± or iterates ± repeatedly. SkillSoft and the SkillSoft logo are trademarks or registered trademarks of SkillSoft in the United States and certain other countries.Loops execute code for each argument supplied. For example. which while it holds true. Introducing and using loops | | Summary | Copyright © 2003 SkillSoft. the if then elif command.

1. Task 1: Writing a function Suppose that you want to create a script that will notify a user by e-mail if specific files have been modified during week days. See if you can type the code indicating the function name and the start of the function. If files have been modified. you need to write a Korn shell script that exits if the date is not a week day.Learning objective After completing this topic. If not files have been modified. To do this. you're required to use conditional expressions and flow control in a shell program. #!/usr/local/bin/ksh #===================== # Function" Check if today is a weekday #====================== MISSING CODE today=$(date '+%A') #====================== check_date . Question Let's say that you want to write a function called check_date that determines whether the current date falls on a weekend. the script must check to see if any files have been modified in a specified directory. Exercise overview In this exercise. you should be able to use conditional expressions and flow control in a shell program. This involves the following tasks: y y writing a function writing the main script 2. it must e-mail the user. First. the script must check the date. If it is a week day. the script must terminate.

Question You want to ensure that the program runs on weekdays See if you can complete the code that allows you to provide an alternative condition for the if statement. #!/usr/local/bin/ksh #================== #Function "Check if today is a weekday #====================== function today=$(date '+%A') if [[$today == Saturday MISSING CODE $today == Sunday ]] then return=false fi } #======================= check_date Answer The operator that will exit the shell script on Saturdays and Sundays is ||. Question You want to ensure that only files modified on weekdays are mailed to the user. #!/usr/local/bin/ksh #===================== # Function" Check if today is a weekday #====================== function check_date { today=$(date '+%A') . See if you can supply the operator that will exit the shell script on Saturdays and Sundays.Answer You either enter function check_date { or check_date { to begin the function definition.

Task 2: Using conditional statements .if [[ $today == Saturday || $today == Sunday ]] then return=false MISSING CODE fi } #======================= check_date Answer The code that allows an alternative condition. in this case. Question The condition you include needs to evaluate to true on weekdays so that the program continues to run on these days. is else. See if you can complete the code that allows this. #!/usr/local/bin/ksh #===================== # Function" Check if today is a weekday #====================== function check_date { today=$(date '+%A') if [[ $today == Saturday || $today == Sunday ]] then return=false else print "Today is a weekday" MISSING CODE } #======================= check_date Answer The code that allows a true return value is else return=true 3.

See if you can complete the code that allows you to call the modify function. Choose the flow control statements that will print out the modified files. return=false check_date if [[ $return == true ]] then print "Finding out if files were modified today" MISSING CODE Answer You type modify to call the modify function. #================ #Function: checks what files are modified today #================ function modify { find /home/vincep ±ctime 1 > logfile if [[ ! ±s logfile ]] then print "No files were modified" modified=false else print "Files were modified" modified=true fi } Question You now want to complete the code so that the program checks to see if any files have been modified in a directory and then outputs any files that have been modified. . you also write this modify function to check if any files have been modified in the last 24 hours. Question You want to print the list of any files that have been modified using the cat command.After writing the check_date function to check if the current day is a weekday.

return=false check_date if [[ $return == true ]] then print "Finding out if files were modified today" modify MISSING CODE fi Options: 1. if [[ $modified == true ]] then print "The modified files:" cat logfile fi 3. . while [[ $modified == true ]] do print "The modified files:" cat logfile done Answer The missing code is if [[ $modified == true ]] then print "The modified files:" cat logfile fi Option 1 is incorrect. The use of the ! operator on the first line means that the condition evaluates as false if files are modified. while [[ $modified == false ]] do print "The modified files:" cat logfile done 4. whereas you need it to evaluate as true. if [[ ! $modified == true ]] then print "The modified files:" cat logfile fi 2.

printing a list of the modified statement accompanied by a message. return=false check_date if [[ $return == true ]] then print "Finding out if files were modified today" modify if [[ $modified == true ]] then print "The modified files:" cat logfile fi fi Table of Contents | Top of page | | Learning objective | | 1. If this test evaluates as true. in which case there will be nothing to print. To avoid infinite looping if the condition is met. The first line tests that files have been modified. The shell script exits if it is a weekend or if no files have been modified. you need to include the following command at the end of the code that is executed by the loop: modified=false You have now created a function that tests whether the current day is a weekday. Option 4 is incorrect. Exercise overview | | 2.Option 2 is correct. Also. | Print | Contents | Close | . SkillSoft and the SkillSoft logo are trademarks or registered trademarks of SkillSoft in the United States and certain other countries. this loop will be infinite. All rights reserved. The shell script then checks if the files in a directory have been modified and outputs these files with the cat command. Option 3 is incorrect. Task 2: Using conditional statements | Copyright © 2003 SkillSoft. the rest of the if fi statement is executed. All other logos or trademarks are the property of their respective owners. if the condition is true. Task 1: Writing a function | | 3. The loop executes if files are not modified.

Functions improve shell programming by y y increasing the speed of code execution organizing shell scripts increasing the speed of code execution Functions execute faster than scripts because they are loaded in memory. When functions are self-contained. For example. 1. As a result. function md { mkdir $1 && 'cd' $1 } When functions are contained within shell scripts.Functions in UNIX shell programming Learning objective After completing this topic. this self-contained function will create a directory and then access that directory. Introducing functions A function is a set of commands grouped together and called by the same name that accepts a number of arguments as input and can return a value. the shell doesn't need to read them from disk each time a script references them. Functions can be self-contained or contained in shell scripts. . you should be able to use functions to improve the efficiency of program code. Functions also consolidate redundant sequences of commands. organizing shell scripts Functions organize shell scripts into modular pieces of code that are easier to develop and maintain than separate commands. you can create a function to print an error message whenever specific errors occur. For example. they need to be called in the main body of the shell script. they can be stored in memory and executed at the command line.

Because functions can have local variables.function name { commands } A simple function named quit is called from the main shell program to quit after printing "Hello world". #!/usr/local/bin/ksh function quit { exit } print "Hello world" quit This code uses a get_time function to return the current time in the format that shell scripts require. #!/usr/local/bin/ksh x=1 function myfunc { x=3 typeset y=4 print "In local print "In local } myfunc print "Outside local print "Outside local function x is $x" function y is $y" function x is $x" function y is $y" Note You can declare functions using the Portable Operating System Interface (POSIX) format shown here to maintain compatibility with the Bash shell. #!/usr/local/bin/ksh function get_time { TIME=$(date +%m/%d/%y-%H:%M:%S) printf "$TIME\n" } get_time You can declare a local variable in a function using the typeset command. Functions that have this format cannot contain local variables. . recursion is possible. All the other function variables are inherited and shared by the Korn shell script. This reduces the need for extra code.

Because they allow you to reuse code Because they are loaded into memory Because they use control flow structures Because they use local variables Answer . try again" . 2.. *) print "Non-numeric input. The return command uses the syntax return variable You can use this script to ensure that the user's input is an integer value and then to return this value for further calculation. 3. This allows you to pass variables to a function and to obtain a return value from the function. #!/usr/local/bin/ksh function get_number { print "Input a number between 1 and 9" read num case $num in +([0-9])) print "Input is numeric" .The syntax for doing this is function_name() { commands } You can use the return command to pass an exit value from a function to the invoking Korn or Bash shell script. esac } get_number print "The number is $num" integer answer=$num*5 print "Five times number is $answer" Question Why do functions improve the performance of shell programs? Options: 1.. 4.

While functions do allow you to reuse code. Option 3 is incorrect. Option 4 is incorrect. it is the fact that the function's code is copied into memory that improves performance. from where it is executed whenever a script calls it. 3. Functions can be defined at any point in a shell script. Option 4 is correct. Option 2 is correct. functions accept one or more arguments. You can store a function in an ordinary text file and use the . This is more efficient than reading the code from disk. 2. Question Identify the true statements concerning functions. Usually. which are supplied after the function name when you call the function. Option 3 is correct. as long as it is before they are first called. 2. You can use the return command to specify a return value for a function. Functions can use local or global variables. command to read it into memory. When a function is first declared it is copied into memory.Functions improve the performance of shell programs because they are loaded into memory. and there is no significant performance gain associated with either. Option 2 is correct. Functions always return the exit status of their last command Functions can be defined within a shell script You can pass arguments to a function You can read self-contained functions directly into memory Answer Functions can be defined within a shell script or read directly into memory. It is common for a function to accept arguments. Uses of functions . 4. Options: 1. Functions don't have to include control flow stuctures. Option 1 is incorrect. Option 1 is incorrect.

a self-contained function ± named get_time ± outputs the time in a specific format. *) print "Non-numeric input. they allow recursion. try again" . function get_time { TIME=$(date +%m/%d/%y-%H:%M:%S) printf "$TIME\n" } used within shell scripts You use functions within scripts to organize data. In the following example. you can use a function to verify that a user inputs the correct data in response to a prompt. Because functions have local variables. Functions can accept arguments and then return values after processing the data.Functions are a form of command that can be y y self-contained used within shell scripts self-contained You use self-contained functions to execute a number of commands from the shell. You normally use functions for commands that are invoked often. as illustrated in the following code: #!/usr/local/bin/ksh function get_number { print "Input a number between 1 and 9" read num case $num in +([0-9])) print "Input is numeric" . esac } get_number print "The number is $num" integer answer=$num*5 print "Five times number is $answer" . You need to read these functions into memory so that you can execute them from the command line.. For example..

it reads and executes it in the current environment. Once you read a function in.You use the . Rather. rather than reading them in each time they are invoked. typeset ±fu function_name Discipline functions manipulate variables. you can invoke it from a shell script using the syntax function shell_script In the Korn shell you can export functions using the typeset ±fx functionname command. you use this syntax. To autoload a function. For example. although you don't call them specifically in shell scripts. function get_number { print "Enter a number from 1-9" read num case $num in ([0-9]) ) print "Thanks" * ) print "Try again!" esac } typeset ±fx get_number You can autoload functions to improve performance. the shell reads in the functions when they are first invoked and keeps them in memory. In this case. When it finds the appropriate file. a script calls a discipline function when it accesses the variable associated with the function. command to read self-contained functions into memory. . to read in the function error_message. To autoload a function. The shell searches each directory in the FPATH variable from left to right for a filename that matches the name of the function. you first need to set the FPATH variable with the name of the directory that stores it. You can define these functions. For example this command will export the get_number function. you type . You generally autoload functions that are not invoked frequently. error_message.

time. esac } while [ $num != [1-9] ] do get_number done ((square=num*num)) print "$num squared is: $square" Options: 1. Question Suppose that you have written a shell script to ensure that users enter an integer value for use in a calculation. the shell calls the discipline functions time. Try again! 6 squared is 36 Answer The output of the script will be as follows: Try again! Thanks 6 squared is 36 .set. * ) print "Try again!" .unset when the variable time is accessed. Thanks 6 squared is 36 2.For example. or unset respectively... Try again! 3. set. and time.get. What do you think the output of this script ± excluding interactive prompts ± will be if a user first enters a text value and then the value 6? #!/usr/local/bin/ksh function get_number { print "Enter a number from 1-9" read num case $num in ([1-9]) ) print "Thanks" . Try again! Thanks 6 squared is 36 4.

All other logos or trademarks are the property of their respective owners. Introducing functions | | 2. SkillSoft and the SkillSoft logo are trademarks or registered trademarks of SkillSoft in the United States and certain other countries. which matches the "catch-all" pattern in the case statement: *) print "Try again!" Option 2 is incorrect. and the code that prints the square of the num variable is executed. The while loop ensures that the get_number function is executed repeatedly until the user supplies a value between 1 and 9. the while loop exits because its condition is met. Uses of functions | | Summary | Copyright © 2003 SkillSoft. The get_number function provides feedback when a suitable variable has been entered. All rights reserved. You can read a function in and then invoke it from the shell. Summary Functions can be self-contained or contained in shell scripts. Table of Contents | Top of page | | Learning objective | | 1.Option 1 is incorrect. | Print | Contents | Close | Using I/O in UNIX shell programs . Once the user has supplied a valid value for the num variable. the shell reads it in when it is invoked rather than each time a Korn shell script invokes it. After autoloading a function. you need to set the FPATH variable with the pathnames to files for autoloading functions. Functions improve shell programming by executing faster than separate commands and by organizing shell scripts into manageable modules of code. Option 3 is correct. To allow the autoloading of functions. You declare functions using the Portable Operating System Interface (POSIX) format to maintain compatibility with the Bash shell. Option 4 is incorrect. The user first enters text.

Learning objective After completing this topic. you should be able to use the UNIX I/O system in shell programs. the standard input is read from the terminal keyboard. standard error The standard error file is where the program reports any errors encountered during execution. to identify standard output (stdout) 2. You need to use file descriptors with some redirectors ± such as the exec command. By default. Understanding I/O control Each program you run from the shell opens files that provide the primary means of communication between it and other processes or programs. The Korn shell automatically assigns the most common file descriptors. which opens specified files. which are y y y 0. 1. By default. you use the following syntax: input 2>standard_error_output You can control program input/output (I/O) ± including the source that a program uses for input and where it sends output and standard error ± using redirection. The files that active programs open are y y y standard input standard output standard error standard input The standard input file provides a way to send data to a program. By default. to identify standard input (stdin) 1. the standard output goes to the terminal display screen. . These files exist for as long as the program runs. to identify standard error (stderr) If you want input to go to standard error. the standard error goes to the terminal display. standard output The standard output file provides a means for the program to output data.

until it encounters the specified word ± in this case. Question You can include user interactivity in a shell script. Larry. To do this. to overwrite an existing standard output file even if noclobber is enabled <. print . In the example more < /etc/passwd. you can include the instruction <text1 in a shell command to instruct the shell to read input from a file called text1 instead of from the terminal keyboard. to redirect standard input from a file <>.You can use the following redirection commands: y y y y y >. The shell reads the input to the command until it encounters a line that contains only the marker string. All the lines it has read ± except for the marker string line ± are then fed to the command as its standard input. and Mary. to redirect standard output to a file >>. It then creates a file called script#4. line by line. the here document feeds instructions to the mail command. echo 2. You use a "here" document to redirect multiple lines from standard input to a command. the shell reads standard input for cat until it reaches a line containing only the string EOF. What command do you think transfers the user's response to memory so that the input can be used for processing? Options: 1. The syntax for a here document is command<<word For instance. to redirect standard error You can instruct the shell to use the content of a file as input. you redirect the standard input using a marker string ( most commonly. the shell sends the content of the password file to the more command for display on the screen. In the example cat > script4 << EOF. For instance. EOF (end-offile). END. to append standard output to a file >|. in a script that sends e-mail to a list of users named Terry.

quote 4. You can modify the behavior of the read command using the following options: y y y y -p The -p option instructs the shell to read an input line from a coprocess. -r The -r option forces the shell not to interpret the backslash (\) as a line continuation character. -s The -s option causes the shell to save a copy of an input line in the command history file. The print command displays the content of a specified string ± the prompt you want the user to respond to ± on screen.3. read Answer The read command transfers the user's response to memory so that it can be used for processing. You can modify its behavior using the following options: y y y y y y y -n -p -r -R -s -un -p -r -s -un . -un The -un option causes the shell to read a specified input line from the specified file descriptor.

-n The -n option prevents the shell from adding an ending newline to the output.The . the code ls /tmp > ~/ls. in the Korn shell you could sort the /etc/passwd file. For instance. and trap any errors in a file called log_errors using the command sort < /etc/passwd > prog_errors 2> log_errors Question Match the redirection operator to its specific function. You can direct the flow of output from a command to a file instead of to the default terminal screen. place the results in a file called prog_errors. Options: . the old version will be overwritten. -r The -r option causes the shell to ignore the backslash (\) escape conventions. you can append content to the end of a file using the >> command. To prevent this.option causes the shell to interpret all strings following the hyphen as an argument. Instead of displaying errors on screen. -s The -s option causes the shell to redirect specified arguments to the history file. Note If the file named ls.out creates a file containing the output ± in this case a listing of the /tmp directory ± of the ls command into a new file called ls. even when the string itself begins with a hyphen. For instance. you can redirect a program's standard error to a file or command.out. -un The -un option causes the shell to redirect arguments to the specified file descriptor.out already exists. -p The -p option causes the shell to redirect arguments to a coprocess. as well as preventing it from interpreting arguments preceded by a hyphen as options. -R The -R option causes the shell to ignore the backslash (\) escape conventions.

. -p -r -s -u Answer You use the ±r option to prevent the backslash (\) being interpreted as a special character in input supplied by the read command. Appends standard output to an existing file B. overwriting an existing file even if the noclobber option is set Answer The > redirects standard output to a file. You can append the output from the ls command to a file named dirlist.txt with this command: ls > dirlist. >> 2.1. If the file already exists and you want to overwrite it despite the noclobber option being set. > 3. You append standard output to a file with the >> operator.txt with this command: ls >| dirlist. you use the >| operator. 2.txt with this command: ls >> dirlist. Redirects standard output to a file C. Redirects standard output to a file. 4.txt Question Which option for the read command do you use if you don't want the backslash (\) to be interpreted as a special character when supplied as input? Options: 1. you can redirect standard ouptut to overwrite an existing file called dirlist. >| Targets: A.txt You can redirect the output from the ls command to a file named dirlist.txt Even if the noclobber option is set. 3.

To cater for the two possible values of the ANON variable ± yes or no ± you need to use an if « else statement to create two conditions. 2. the backslash causes special characters to be treated as literals. Programming with I/O control Let's say that you want to write a program to automate file transfer across a network for users. you create an echo « read loop inside a while « do statement. To ensure that the value that a user enters is either y or n. During planning. . The read ±u option is used to specify the file descriptor used to provide input.Option 1 is incorrect. the statement will create two new variables ± FTPLOGIN and PASSWD. the commands in the loop execute to prompt the user for a correct response. A user may need to transfer a file to an anonymous FTP site ± which doesn't require the user's username or password ± or to a secure site ± which does require authentication. If the option is not inserted. The read ±s option will cause input to be saved in the command history file. The loop exits only when the user enters a correct value. you decide to divide the program into two logical sections. Option 4 is incorrect. Option 3 is incorrect. Option 2 is correct. The default is standard input. The first section will gather user data ( such as a user's username and password ( and the second section will use this data to connect to a server and transfer local files to the server. If the value of ANON is yes. Using an echo command. The read ±p option is used to accept input from a co-process spawned using the |& operator. Each time a user enters a value other than y or n. you start interaction with the user by printing the question Do you want to perform an anonymous ftp [y/n]: to the screen. So your code first needs to determine how the user intends to transfer a file. as in read ±u 0. The value of FTPLOGIN will be "anonymous" and PASSWD won't contain a value. which the program then reads into memory as the value of the ANON variable. You then use the read command to create a new variable called ANON to place the user's reply ± yes or no ± in memory.

You decide to use two echo « read statements to allow the user to supply these values. 4. . Once the program has obtained user authentication details. it needs to prompt the user to supply the address of the server to which a file is to be transferred and the name and location of this file. Which variables do you think you need to specify in the statements? Options: 1. 3. the user needs to provide authentication details to log in to the remote server. please: " read ANON done if [[ $ANON != y ]] then FTPLOGIN=anonymous PASSWD=" " else echo "Enter the username to use: " read FTPLOGIN echo "Enter the password to use: " read PASSWD fi Question If the FTP session that a user requests is not anonymous. ANON FTPLOGIN PASSWD A new variable to store the user's login details Answer You need to specify the FTPLOGIN and PASSWD variables to retrieve the user's username and password. 2.echo "Do you want to perform an anonymous ftp [y/n]: read ANON while [[ $ANON != y && $ANON != n ]] do echo "Enter y or n.

sh Do you want to perform an anonymous ftp [y/n]: . you use two print « read statements. You follow the screen prompts and the file is transferred without error. To do this. please: " read ANON done if [[ $ANON != y ]] then FTPLOGIN=anonymous PASSWD=" " print "Enter the address of the FTP server: " read FTPSERVER print "Enter the file to transfer: " read FILE To allow the program to establish an FTP session with a server.To make the program do this. you write a here document.2. you need to specify the ftp commands that the user's local computer must use to make the actual file transfer.END open $FTPSERVER quote USER $FTPLOGIN quote PASS $PASSWD binary cd /home/gregl put $FILE END ) Let's say that you want to test your program by anonymously sending a file called case./ftp. ( ftp -n <<. echo "Do you want to perform an anonymous ftp [y/n]: read ANON while [[ $ANON != y && $ANON != n ]] do echo "Enter y or n. in which you create two new variables ± FTPSERVER and FILE ± to contain the new information. which terminates itself and the FTP program when it reaches the END marker.100.2. $ .sh to a server at the IP address 190.

Option 2 is correct. The echo command will merely print the string NAME to the screen. Option 3 is incorrect. 4.100. typeset ±x is used to export a variable. 3. print "Enter the account name: " Missing_code NAME Options: 1. Identify the command that completes the code that obtains an account name from standard input. and input at the prompt will be assigned to the NAME variable. The << operator is used to open a here document. Option 1 is incorrect. Option 4 is incorrect. The read command will provide a prompt. echo read typeset -x << Answer You use the read command to obtain the account name from standard input.2 Enter the file to transfer: case. standard output. and standard error. .2.sh $ Question You are writing a script to automate the process of adding a user account to the system. You need to use file descriptors with some redirectors. You can direct the flow of output and errors from a command to a file instead of to the default terminal screen. 2.y Enter the address of the FTP server: 190. not to receive input. These files are standard input. Summary Programs that run from the shell open files that provide the primary means of communication between it and other processes or programs.

Introducing the select command The select command allows you to create a simple menu that users can use to interact with a program. Understanding I/O control | | 2. 1. You specify a select command using the syntax shown here. Programming with I/O control | | Summary | Copyright © 2003 SkillSoft.You can write programs that use input/output (I/O) control. | Print | Contents | Close | Using menus in UNIX shell programs Learning objective After completing this topic. Table of Contents | Top of page | | Learning objective | | 1. SkillSoft and the SkillSoft logo are trademarks or registered trademarks of SkillSoft in the United States and certain other countries. followed by a do « done statement loop. you can create a program that automates file transfer across a network for users. Note The select command is available only in the Korn shell and version 1. The menu contains numbered items and displays a prompt message. For example. All other logos or trademarks are the property of their respective owners. In the syntax. The command will associate the names you specify with the commands contained in the loop. All rights reserved. . you should be able to create user menus with the select command and use them in shell programs. This program gathers data and then uses this data to connect to a server and then transfer local files to the server. you need to supply a list of menu item names.14 and later of the Bash shell.

run a text editor. Creating menus Let's say that you want to write a shell script that allows users to view the files in a directory. return. Whenever a shell displays a menu prompt. or EOF marker Stores the selected option in a built-in variable named REPLY Answer Correct ranking Option B D A C Description Prompts the user for a number Stores the selected option in a built-in variable named REPLY Executes the statements in the body of the command Breaks on encountering a break. meaning "which number?" ( to . or exit the script. You decide to change the default menu prompt ( which is #?.select variable in name1 name2 « namen do commands done Question The select command generates a menu containing each specified item in a numbered list. exit. exit. Options Option A B C D Description Executes the statements in the body of the command Prompts the user for a number Breaks on encountering a break. return. See if you can place the steps that the select command performs when a user selects a menu item in the correct sequence. it uses a default prompt character stored in a shell variable named PS3. or EOF marker 2.

#!/usr/local/bin/ksh PS3="Select an option [1-3]> " select OPTION in "Show files" "Run editor" "Exit" The do « done statement in the select command needs to specify actions that correspond to a user's selection of each of the three specified menu items.a new prompt that you specify. its corresponding value is recorded in the user-defined OPTION variable and stored in the built-in REPLY variable.. and "Exit". What command do you think you can use to insert dummy text for these options? Options: 1. In this case. echo read select quit . in the order in which they are to appear on screen. You do this using an if . else statement. 4. #!/usr/local/bin/ksh PS3="Select an option [1-3]> " You name the menu items "Show files". To do this. When the user selects an option. #!/usr/local/bin/ksh PS3="Select an option [1-3]> " select OPTION in "Show files" "Run editor" "Exit" do if [[ $REPLY = 3 ]] then exit Question Let's say that you want to test the menu at this point before adding functionality to the first two menu items.. 2. you set the PS3 variable to the text you want to appear as the prompt. you first specify that if the user chooses the third menu option ( the Exit option for quitting the menu ( the select command will execute the exit command. 3. "Run editor".

/select. This returns the message "You chose to Show files" and returns to the menu./select. To test the code at this point ± without adding functionality for options 1 and 2 ( you add an echo statement that is printed if a user selects any item other than the third menu item. it generates a menu with labeled options and the changed prompt text you've specified. you need to number the menu items manually with . #!/usr/local/bin/ksh PS3="Select an option [1-3]> " select OPTION in "Show files" "Run editor" "Exit" do if [[ $REPLY = 3 ]] then exit else echo "You chose to $OPTION" fi done When you execute the select command. $ .sh 1) Show files 2) Run editor 3) Exit Select an option [1-3]> Let's say that you test the menu by selecting option 1. instead of an if « else statement.sh Show files Run editor Exit Select an option [1-3]> You chose to Show files Select an option [1-3]> The example here shows a dummy menu generated by a select command that uses the case command to structure the menus. $ .Answer You can use echo statements to print dummy option text to test the functionality of the menu. When you use the case command.

2 ) echo "Do action 2" . 3 ) echo "Do action 3" . The case command can be used instead of if then else statements to execute code based on the user's menu selection. The select command can be combined with the case command 3. esac The output of the dummy menu using the case command is shown here.echo statements and you need to terminate each command line with a double semicolon (. . Options: 1. The prompt used by the select command is determined by the PS3 built-in variable 2../case. Menu item one 2.. The select and case commands are often combined. Menu item one" echo "2. $ . Menu item two" echo "3. The select command is available in the Korn and C shells 4. The Korn shell default is #? Option 2 is correct. The shell's interactive prompt is determined by the PS3 variable. Menu item two 3.. and select command input is stored in the REPLY variable. #!/usr/local/bin/ksh echo "1. The select command uses the REPLY variable to store user input Answer The PS3 variable determines the prompt used by the select command.). Option 1 is correct.. Menu item three Choose an option [1-3] Question Identify the true statements about the select command. Menu item three" echo "Choose an option [1-3]" read MENUITEM case $MENUITEM in 1 ) echo "Do action 1" .sh 1.

All rights reserved. but is more globally applicable. All other logos or trademarks are the property of their respective owners. Table of Contents | Top of page | | Learning objective | | 1. Introducing the select command | | 2. SkillSoft and the SkillSoft logo are trademarks or registered trademarks of SkillSoft in the United States and certain other countries. but not the C shell. . The value entered by the user is stored in the REPLY variable.14 and later of the Bash shell. The select command is available in the Korn shell and in version 1. The select command is supported by the Korn shell and recent versions of the Bash shell. The case command provides similar functionality. you're required to create a shell script that generates a simple menu. The select command presents the user with a numbered menu and a prompt. | Print | Contents | Close | Writing a UNIX shell program using I/O commands Learning objective After completing this topic. Creating menus | | Summary | Copyright © 2003 SkillSoft. Both the case and select commands allow you to specify behavior based on the value of a variable.Option 3 is incorrect. you should be able to write an interactive program that makes use of standard input and output. Exercise overview In this exercise. Option 4 is correct. Summary You can use the select command in scripts to create basic menus.

#!/usr/local/bin/ksh# MISSING CODE "Choose a menu item [1-3]>" Result You enter PS3= to change the prompt text. or quit the program using a simple menu.This involves the following tasks: y y specifying the menu items adding functionality to the menu Task 1: Specifying menu items Let's say that you want to create a program that allows users to view files in the current directory." See if you can type the code that will change the prompt. Step 2 of 2 See if you can type the command that will generate a menu.sh View files Launch Editor Quit Choose a menu item [1-3]> Step 1 of 2 Let's say that you want to specify the menu prompt "Choose a menu item [1-3]>. $ ./editor. edit a specified file. #!/usr/local/bin/ksh# PS3="Choose a menu item [1-3]>" MISSING CODE ITEM in "View files" "Launch Editor" "Quit" Result You enter the select command to generate a menu. Task 2: Adding functionality to options .

Option 2 is correct.Let's say that you now want to specify the commands that the select command must call when a user selects one of the menu items. 4. Option 1 is incorrect. The ITEM variable needs to be expanded using the $ITEM syntax. reduces the likelihood of typographical errors. REPLY is a variable returned by the select command. The case command executes code based upon the value of a variable ± in this case the REPLY variable returned by the select command. it is more efficient to use the REPLY variable. case case case case REPLY in $REPLY in ITEM in $ITEM in Result You enter case $REPLY in to specify the menu structure. Option 3 is incorrect. 3. #!/usr/local/bin/ksh# PS3="Choose a menu item [1-3]>" select ITEM in "View files" "Launch Editor" "Quit" do Step 1 of 4 Choose the most appropriate code to start structuring the menu. so you need to use the $REPLY syntax to expand the variable. which contains a number assigned to each item in the menu that is created by the select command. Option 4 is incorrect. Step 2 of 4 . it requires you to specify each possible value for the ITEM variable listed in the select command. Furthermore. 2. #!/usr/local/bin/ksh# PS3="Choose a menu item [1-3]>" select ITEM in "View files" "Launch Editor" "Quit" do MISSING CODE Options: 1. Although this is a possible solution. Using the REPLY variable.

The pwd command provides the name of the current directory as output. To perform command substitution.. 1) echo "The current directory is (pwd)" ls . The ls command then lists the contents of the current directory. The break command will exit the case loop. causing the program to end once the user has viewed the contents of the current directory. Option 1 is correct... #!/usr/local/bin/ksh# PS3="Choose a menu item [1-3]>" select ITEM in "View files" "Launch Editor" "Quit" do case $REPLY in MISSING CODE Options: 1. Option 3 is incorrect.. Step 3 of 4 Choose the code that you think will specify that the second menu item is to load a specified file in the vi editor.Choose the code that you think will retrieve a listing of the current directory if a user selects the first menu item. 1) echo "The current directory is $(pwd)" ls break . Command substitution is used to insert the output into the string that is sent to standard output by the echo command. 2. and will allow to then choose other menu options. 1) echo "The current directory is $(pwd)" ls . Option 2 is incorrect. the brackets that contain the command must be preceded by the $ special character. 3. . Result The code that will retrieve a listing of the current directory is shown here: 1) echo "The current directory is $(pwd)" ls .

2) echo "Name the file to edit" read FILE vi $FILE . This command will open the vi editor with a file named FILE in the edit buffer. the value the FILE variable is used as an argument to the vi editor. The 2) denotes that the subsequent code is executed if $REPLY=2. The read command allows the FILE variable to be set using standard input. To achieve the desired result of expanding the FILE variable set using the read command. Option 1 is incorrect. . Once it has been set. 2) echo "Name the file to edit" read $FILE vi FILE .. MISSING CODE Options: 1. The echo command provides a prompt. you need to perform variable expansion using the $FILE syntax.. Result The code that will load a specified file in the vi editor is shown here: 2) echo "Name the file to edit" read FILE vi $FILE .#!/usr/local/bin/ksh# PS3="Choose a menu item [1-3]>" select ITEM in "View files" "Launch Editor" "Quit" do case $REPLY in 1) echo "The current directory is $(pwd) ls ... 2. Step 4 of 4 Choose the code that you think will exit the menu if a user selects the third menu item. Option 2 is correct.

3) break .. #!/usr/local/bin/ksh PS3="Choose a menu item [1-3]>" select ITEM in "View files"\ "Launch Editor"\ . 2.. 2) echo "Name the file to edit" read FILE vi $FILE . MISSING CODE Options: 1. When you have specified the functionality for each menu item. not one.#!/usr/local/bin/ksh# PS3="Choose a menu item [1-3]>" select ITEM in "View files" "Launch Editor" "Quit" do case $REPLY in 1) echo "The current directory is $(pwd) ls . or for loop. 3. This code will simply result in nothing being executed when the third option is selected ± but the loop will not be exited and the user will be prompted to choose a menu item again. Option 1 is incorrect.. This code will result in a syntax error. Each case statement must end with two semicolons. while. you end the case and do commands and print a statement to screen. Result The code that will exit the menu if a user selects the third menu item is 3) break . 3 break .. Option 3 is correct. Option 2 is incorrect. 3) . crashing the program.. The break command is used to exit a case.

and indentation. All other logos or trademarks are the property of their respective owners. | Print | Contents | Writing legible UNIX shell scripts Abstract This article describes recommended practices for writing human-readable shell scripts. .. 3) break . All rights reserved. it's a good idea to lay them out so that human readers can read them easily. esac done Table of Contents | Top of page | | Learning objective | | Exercise overview | | Task 1: Specifying menu items | | Task 2: Adding functionality to options | Copyright © 2003 SkillSoft. white space. including the use of comments.."Quit" do case $REPLY in 1) echo "The current directory is $(pwd) ls . SkillSoft and the SkillSoft logo are trademarks or registered trademarks of SkillSoft in the United States and certain other countries. Introduction In addition to ensuring that your shell scripts contain accurate code. 2) echo "Name the file to edit>" read FILE vi $FILE ..

for example. but they will be more transparent. Note that dots (. you should insert a comment like the following: # This function reads a customer's name and contact details from user input. it's a good idea to insert them liberally so that other users can work out what each part of your script is for.) and underscores (_) don't split a name. Although comments aren't essential to the functioning of a script. It's also a good idea to insert a comment at the beginning of a script. Variable names If you name variables and functions after the tasks they perform. an appropriate comment for explaining a specific variable is bookingID=$2 #unique ID number for the new booking . and they allow other shell programmers to read and understand your script. an appropriate comment might be # This script obtains data about one or more new bookings using input functions and then inserts the data as a new entry in the bookings table. This allows you to create similar variables ± such as package_name and read.data. you can add a comment that explains its function.flight. This is especially useful if the variable is an important global variable or if it performs a complex function in a script. This may require that names be quite long. For example.You can use blank lines and indentation to indicate the structure of the script.data function. you could call it customer_name. When you create a variable. For example. This comment needs to explain the general purpose and structure of the script. and you can give meaningful names to variables and functions so that the reader can understand their purposes. A function that reads customer data could be read. If. it becomes much easier for readers to figure out what's going on in a script. This allows you to insert comments in a script.customer.customer. At the beginning of the read. These techniques make it easier for you to debug the script after you've written it. so they're a good way to build names that contain multiple words. for example.data ± without causing any confusion. you need a variable to contain the name of a customer. Comments The shell disregards any line in a script that begins with a hash (#).

You can split the main script at any point you choose ± for example when one task has been accomplished and another begins. variable. both from each other and from the main script. You should do this for any lines enclosed in a loop or an if statement. You should insert explanatory comments wherever necessary so that readers know what each function.White space Except for spaces in individual command lines. To help human readers understand the script. You can also make the structure of the script easier to understand by using blank lines and indentation. the UNIX shell ignores white space in scripts. There's no such thing as a script with too much white space ± empty lines can only make a script more readable and reduce eye strain for the reader. You can insert empty lines and spaces before lines of code without affecting the running of a script. Indentation Because the shell doesn't respond to initial spaces at the beginning of a line. so that the beginning and the end of the statement are obvious to the reader. This is useful if you want to make a script more readable by separating functions. you should use variable and function names that reflect the purposes of the corresponding variables and functions. you should ensure that it's readable to human readers. or script is for. you can indent lines by a number of spaces. This example of an if statement shows sensible use of indentation: if [$bool1 = n] then rmdir /shared/$tour echo "Rerun add_tour to start again." exit else touch /shared/$tour/status$tour chmod 666 /shared/$tour/status$tour fi Summary When writing a script. Table of Contents | Top of page | | Abstract | .

The more complex a script is. you should be able to explain how to debug shell scripts. 4. For this reason. Troubleshooting principles Once you've written a shell script ± unless it's a very simple one ± it's likely to contain a few bugs. the more time you'll have to spend debugging it. Arithmetic substitution Function calls and arguments Program flow Variable values . SkillSoft and the SkillSoft logo are trademarks or registered trademarks of SkillSoft PLC in the United States and certain other countries. All other logos or trademarks are the property of their respective owners. You can reduce the effort of debugging by carefully examining your script at the design stage. | Print | Contents | Close | Debugging and error-handling UNIX shell scripts Learning objective After completing this topic. 2. it's very useful to structure the script in a way that makes it easy for you to make sense of it. All rights reserved. Question What do you think you need to keep track of when you analyze a script at the design stage? Options: 1. 1.| Introduction | | Variable names | | Comments | | White space | | Indentation | | Summary | Copyright © 2003 SkillSoft PLC. 3.

Once you've sketched the program flow for a script and have eliminated any logical problems at the design stage. you may encounter the following types of errors: y y y logical errors resource errors syntax errors logical errors Logical errors occur as a result of errors in program flow. a script may refer to a file that doesn't exist or it may need to modify a file to which it doesn't have write permissions. including where they are used and what values they're likely to have. Copying Copying Copying Copying file file file file file file file file @a @a @a @a to to to to backup backup backup backup directory« directory« directory« directory« resource errors Reference errors occur when scripts require resources that they can't access. you should test a wide range of input values ( including completely inappropriate values ( to see how the script responds.Answer You need to analyze the logical flow of your script. you write the script code. For example. a script may fail to terminate because it's caught in a logical loop. Then you try running the script. For example. You also need to keep track of variables you've declared. For example. $ user_backup user_backup[3]: syntax error: 'while' unmatched $ . you need to be aware of the functions that should be called at each stage and of which arguments these functions should use. or it may be passing a string to a function that performs integer arithmetic. When testing a script. $ user_backup cp: file: No such file or directory $ syntax errors Syntax errors occur as a result of lexical errors ( such as misspelled variable names and parentheses or quotes that haven't been closed ( in scripts. If it requires user input.

. if it repeats in a predictable way. However. Options: 1. If you can't get the error to repeat. Once you've established what the effects of a bug are. The program is caught in a loop that fails to finish 3.If one of your test runs of a script produces an error. you can begin finding a way to fix the bug. Resource error C. The program tries to write to a directory that doesn't exist Targets: A. such as passing improper arguments to functions or failing to terminate loops. Syntax error Answer An infinite loop is an example of a logical error. you need to find out why the exit conditions for the loop aren't being met. Once you've located the cause of a bug. Perhaps it's because a variable value is wrongly assigned at some other point in the script. and not using the correct format for commands. The program contains an opening quote that isn't closed 2. or it may involve rewriting sections of code. If the script gets stuck in a logical loop. This may be as simple as correcting a spelling mistake. you can't make any further progress towards solving the problem. an attempt to write to a non-existent directory is a resource error. Logical error B. this indicates a fixable bug. for example. Logical errors result from design flaws. you should try to reproduce the error by running the script again with similar input. Syntax errors are generated by mistyping variable or command names. You first need to find the place in the script at which things begin to go wrong. Question Match the examples to the corresponding error type. and if a set of quotes isn't complete a syntax error will be generated. you can begin looking for its causes.

Option 2 is incorrect. The easiest and simplest way to track variables is by introducing large numbers of echo statements into a script. or nonexistant filesystem resources ± are usually encountered during the writing and testing of a program. Logical errors are usually the result of design flaws. Option 3 is incorrect. Tracking variables Finding the place in a script that's causing a bug is the most difficult part of debugging. Resource errors 3. Logical errors 2. 2. Syntax errors Answer Logical errors can usually be minimised by planning your programs carefully at the design stage. so they aren't encountered at the design stage. Option 1 is correct. $ echo "customerID = $customerID" customerID = 411 $ . Question Which of the following types of error can be minimized at the design stage of writing a program? Options: 1. You use the echo statements to output the name and value of a variable at different stages in the script.Resource errors result from a script not being able to access external commands or filesystem locations ± either because they don't exist or because the requisite permissions aren't in place. Syntax errors are only encountered once you start to write a program. you need to track changes in variable values and the direction of program flow. Preparing your program in pseudocode helps to eliminate this type of error. Resource errors ± such as incorrect permissions. To do this.

info () { > echo $* > new_entry[0]=$1 > new_entry[1]=$2 > new_entry[2]=$3 > new_entry[3]=$4 > } $ This example shows an echo statement in a loop. while $count<$total do name=new_entry[0] touch "$name _data" count+=1 # echo "iteration $count. Traps are statements that execute if the script receives a particular signal. while (($count<$total)) do name=new_entry[0] touch "$name _data" count+=1 echo "iteration $count. Statements that assign values to variables . Once you've finished debugging a script. name is $name" done You can use traps to track a particular variable or set of variables. you can disable the echo statements by commenting them out.For example. Each time the loop executes. this echo statement at the beginning of a function displays the values of any arguments passed to the function. the echo statement displays the current value of two variables. Question What kind of statements do you think you need to execute in traps when you're debugging a script? Options: 1. This allows you to re-enable them if you need to debug the script again in the future. read. name is $name" done Detailed output from echo statements is necessary for debugging only.customer.

you use another trap statement without specifying a command. The most relevant traps for debugging are y y y DEBUG The DEBUG trap causes a statement to execute each time a line of code in the script executes. if its exit status is non-zero. DEBUG EXIT ERR . Statements that exit the script Answer When you debug a script using traps. If you want a trap to remain active throughout a script. but it doesn't allow you to trace them through the statements that lead up to that point in a script. You use this syntax for trap statements. $ trap showvars DEBUG A trap is active from the position of the trap statement onwards. you need to enter the trap statement at the beginning of the script. Statements that echo an error message 3. you use the DEBUG trap to run the showvars function after each script statement executes. trap command signal In this example.2. Statements that echo variable values 4. This allows you to display the value of a variable every time the script executes a statement. you need to use the traps to run statements that echo variable values. This is especially useful if you're dealing with an error that causes a script to exit prematurely because it allows you to display the values of important variables immediately before the script crashes. This allows you to view variable values at the point at which errors occur. To deactivate a trap. EXIT The EXIT trap causes a statement to execute when a script exits. ERR The ERR trap causes a statement to execute whenever a statement in the script causes an error ± in other words.

Options: 1. This function might contain commands that display the values of all variables and the line number of the last executed statement. You can include echo commands in your code without affecting control flow You can use the echo command to rename variables You use the echo command to print a variable without modifying its value You use the # symbol to turn echo commands into comments Answer The echo command does not modify the values of variables and doesn't affect control flow within scripts. so it is useful for monitoring variable values in order to debug programs.DEBUG In this example. Question You have written a shell program that creates several temporary files. The echo command can't modify the value of variables passed to it in arguments. Option 3 is correct. you use the EXIT trap to run the exitmsg function if the script receives an EXIT signal. for instance.$ trap . Option 2 is incorrect. It doesn't affect control flow. Option 4 is correct. $ trap exitmsg EXIT Question Identify the true statements about the echo command. 3. but it can't be used to rename variables. The echo command simply prints any arguments to standard output. Which signal do you specify for the trap command? . Any line in a shell script that is preceded by a # is treated as a comment. 4. You want to use the trap command to remove these files if the program exits unexpectedly. The echo command will print the value of any variable passed to it as an argument. 2. so is useful for debugging programs. You use the # symbol to turn echo commands into comments. including lines containing the echo command. Option 1 is correct.

Option 1 is incorrect. This is useful when you want to check for syntax errors or when you suspect that a bug may hang the system. EXIT Answer You use the EXIT signal if you need to execute code when a program exits. This is a powerful way of detecting bugs that occur in the substitution stages of a statement. verbose The verbose option echoes all input that a script receives to the standard error file. you can set debugging options when you run it. The EXIT command is used to create a trap that executes code ± in this case code that removes temporary files ± when a program terminates. Option 2 is incorrect. Option 3 is correct. The DEBUG signal is used to create a trap that executes code after every command in the scripts is executed. ERR 3. This can help you to locate a bug by allowing you to identify which input the script received immediately before an error occurred. Advanced debugging techniques To assist in debugging a script. . The specified code will be executed even if the program terminates unexpectedly. or command substitution. arithmetic. 3. DEBUG 2. The following shell options are useful for debugging: y y y noexec verbose xtrace noexec The noexec option causes the shell to read a script without executing any commands. and it echoes each stage of variable. The ERR signal is used to create a trap that executes code after every error command. whether or not the error causes the program to exit. xtrace The xtrace option echoes each statement in a script as it's executed.Options: 1.

The xtrace prompt ± in this case a plus sign (+) ± indicates how many levels of substitution are occurring for a particular line. noexec 2. Question Which debugging option do you think allows you to view the input that a script receives? Options: 1. $ set -x To unset a debugging option. sets the xtrace option. verbose 3. $ ((res = 36/4 + $i)) + let res = 36/4 + 3 $ Note You can customize the xtrace prompt using the PS4 environment variable. The code shown here unsets the verbose option. for example. The example shows one level of variable substitution in which the number 3 is substituted for the variable i. $ set -o verbose You can run the set command without the -o option. The code shown here sets the verbose option.This example of xtrace output shows how stages of execution are displayed. you use the set +o command. This code. xtrace Answer . You set debugging options using the set command with the -o option. $ set +o verbose Note You can't unset the noexec option because it prevents the set +o command from executing. You do this by using the first letter of the debugging option.

To run the Bash debugger on a script. The most powerful tool for debugging a script is a debugging script. you run a session of the Bash shell and specify the -debugger option. A debugging script appends itself to the target script and enables various debugging tools. . The noexec option reads commands without executing them. xtrace Answer The xtrace option allows you to monitor substitution as commands in a script execute. verbose 3. A debugging script allows you to y y y y start a script with debugging options cause a script to exit under specified conditions display data if a script crashes change a script so that you can test debugging solutions You can write your own debugging script. For example. The verbose option causes input to be displayed as it is read. $ bash --debugger add_pkg_files Question Which debugging option allows you to monitor substitution as commands in a script execute? Options: 1.The verbose debugging option allows you to view the input that a script receives. It's useful for verifying input. but some shells provide an existing debugger. It's useful for discovering syntax errors. The xtrace option displays each command as it is executed and is the most appropriate option for general debugging. Option 1 is incorrect. the Bash shell provides the Bash debugger. noexec 2. Option 2 is incorrect. Option 3 is correct.

A debugging script may help you locate the source of a logical error. Handling user errors If you're developing a script that requires input from users. Option 4 is correct. You can use it to enable debugging options and display data when a script exits unexpectedly. A debugging script appends itself to the target script You can use a debugging script to automatically correct logical errors You can use a debugging script to display data when a script exits unexpectedly You can use a debugging script to enable debugging options Answer A debugging script appends itself to the target script. you need to include statements that check the input to make sure it makes sense. 4. Option 2 is incorrect. 3. 4. When you execute a debugging script you supply the target script as a parameter. Exit the script 2. For example.Question Identify the true statements about debugging scripts. Print an error message . The debugging code is appended to the code of the target script. but it won't correct it. Options: 1. Option 1 is correct. Question What do you think error-handling code needs to do if a user enters inappropriate input? Options: 1. Option 3 is correct. You can use a debugging script to set shell options ± such as the xtrace option ± that facilitate debugging. an input function that reads a time shouldn't accept hours lower than zero or higher than 24. A debugging script can be used to set traps that print useful data ± such as the values of variables ± when a program exits unexpectedly. 2.

You can locate bugs by inserting echo statements that allow you to trace the values of variables at different points in the script's execution. Restart the script Answer If user input doesn't fit into the range of input that makes sense.date () { > echo "Enter month:" > read month > if ((month<0)) | ((month>12)) > echo "Invalid month!" > exit > fi Summary When you write complex shell scripts. It checks the input to ensure that it makes sense and displays an error message and exits if it doesn't fit into the required range of values. Print variable values 4. the error-handling code in the script should provide a simple error message and exit the script. they frequently contain bugs. which incorporate various debugging tools. You can set debugging options when you run a script. When you write scripts that accept user input. This example shows part of a function that reads a date from user input.3. but you need to remove other bugs after writing. Troubleshooting principles | . you should include statements that test the input to make sure it makes sense. These allow you to investigate how the script runs. Table of Contents | Top of page | | Learning objective | | 1. read. To do this. You can avoid some bugs by checking program logic thoroughly before you write a script. you need to find the place in the script that causes the bug and then formulate a solution that fixes it. You can also use debugging scripts. You can also use traps to display variable values when certain conditions occur.

In its current state. Exercise Your assignment for this exercise is to find and eliminate all bugs in the script. All other logos or trademarks are the property of their respective owners. Advanced debugging techniques | | 4. Task list Number Instructions 1 Remove the bugs from the following script: #!/usr/local/bin/ksh DirPath="/home/shared/" Exist=0 while [[ $Exist -ne 0 ]] do . SkillSoft and the SkillSoft logo are trademarks or registered trademarks of SkillSoft in the United States and certain other countries. If your computer doesn't have an application or applications required to carry out the exercise tasks. the script contains two logical errors and three syntax errors. you can proceed to the next topic. Tracking variables | | 3. However.| 2. you've run the script and discovered that it has bugs. It allows a user to specify the directory's name and to undo the creation process if they've made a mistake. or if you would prefer to perform the exercise at another time. Handling user errors | | Summary | Copyright © 2003 SkillSoft. All rights reserved. Scenario You've written a script that creates a shared directory. | Print | Contents | Exercise: Debugging a UNIX shell program A note about exercises This exercise is designed for practice use and does not contain new learning content.

Please Enter Another Directory" else Exist=0 fi done clear mkdir -m 777 $DirPath$DirName echo "The $DirName directory has been created in $DirPath. . All rights reserved. All other logos or trademarks are the property of their respective owners. Table of Contents | Top of page | | Scenario | | Exercise | Copyright © 2009 SkillSoft. Are you happy with this?" read -p "[y/n]" BOOL1 clear if [ $BOOL1 = n ] then rmdir $DirPathDirName echo "$DirName has been removed" exit else touch $DirPath$DirName/status$DirName chmod 666 $DirPath$DirName/status$DirName if Review your solution and.Task list Number Instructions echo "*************************************************** Welcome. when you are satisfied with it. $USER Please type the Directory Then press Enter:" read DirName if [[ -d $DirPath]]. then Exist=1 echo "*************************************************** DIRECTORY EXISTS. SkillSoft and the SkillSoft logo are trademarks or registered trademarks of SkillSoft in the United States and certain other countries. open the solution page.