Answers to Even-Numbered Exercises

Similar documents
Answers to Even-numbered Exercises

Unix Sampler. PEOPLE whoami id who

Thirty Useful Unix Commands

Lecture 4: Writing shell scripts

Unix Shell Scripts. Contents. 1 Introduction. Norman Matloff. July 30, Introduction 1. 2 Invoking Shell Scripts 2

BASH Scripting. A bash script may consist of nothing but a series of command lines, e.g. The following helloworld.sh script simply does an echo.

USEFUL UNIX COMMANDS

CPSC2800: Linux Hands-on Lab #3 Explore Linux file system and file security. Project 3-1

Introduction to Shell Scripting

Bash shell programming Part II Control statements

Using SVN to Manage Source RTL

CS Unix Tools & Scripting Lecture 9 Shell Scripting

An Introduction to the Linux Command Shell For Beginners

Shell Scripts (1) For example: #!/bin/sh If they do not, the user's current shell will be used. Any Unix command can go in a shell script

Extreme computing lab exercises Session one

LECTURE-7. Introduction to DOS. Introduction to UNIX/LINUX OS. Introduction to Windows. Topics:

Introduction to the UNIX Operating System and Open Windows Desktop Environment

Unix Scripts and Job Scheduling

Hadoop Hands-On Exercises

Systems Programming & Scripting

An Introduction to Using the Command Line Interface (CLI) to Work with Files and Directories

Lab 1: Introduction to C, ASCII ART and the Linux Command Line Environment

Linux command line. An introduction to the Linux command line for genomics. Susan Fairley

CS 2112 Lab: Version Control

Using Parallel Computing to Run Multiple Jobs

Mass Deploying Bomgar Software to Macs

CSIL MiniCourses. Introduction To Unix (I) John Lekberg Sean Hogan Cannon Matthews Graham Smith. Updated on:

HP-UX Essentials and Shell Programming Course Summary

SFTP SHELL SCRIPT USER GUIDE

Hadoop Shell Commands

Hadoop Shell Commands

Running your first Linux Program

RECOVER ( 8 ) Maintenance Procedures RECOVER ( 8 )

Unix the Bare Minimum

New Lab Intro to KDE Terminal Konsole

Command Line - Part 1

An Introduction to Using the Command Line Interface (CLI) to Work with Files and Directories

Command Line Crash Course For Unix

Answers to Even- Numbered Exercises

Hands-On UNIX Exercise:

Using SVN to Manage Source RTL

Command-Line Operations : The Shell. Don't fear the command line...

grep, awk and sed three VERY useful command-line utilities Matt Probert, Uni of York grep = global regular expression print

Automating admin tasks using shell scripts and cron Vijay Kumar Adhikari.

CTIS486 Midterm I 20/11/ Akgül

Exercises: FreeBSD: Apache and SSL: pre SANOG VI Workshop

A Crash Course on UNIX

A UNIX/Linux in a nutshell

Extreme computing lab exercises Session one

Hadoop Hands-On Exercises

Syntax: cd <Path> Or cd $<Custom/Standard Top Name>_TOP (In CAPS)

1 Basic commands. 2 Terminology. CS61B, Fall 2009 Simple UNIX Commands P. N. Hilfinger

Kleine Linux-Tricks - schneller ohne Aufwand

SVN Starter s Guide Compiled by Pearl Guterman June 2005

CPSC 2800 Linux Hands-on Lab #7 on Linux Utilities. Project 7-1

WES 9.2 DRIVE CONFIGURATION WORKSHEET

Installing IBM Websphere Application Server 7 and 8 on OS4 Enterprise Linux

Introduction to Git. Markus Kötter Notes. Leinelab Workshop July 28, 2015

Cisco Networking Academy Program Curriculum Scope & Sequence. Fundamentals of UNIX version 2.0 (July, 2002)

HDFS File System Shell Guide

DOS Command Reference

Exercise 1: Python Language Basics

Birmingham Environment for Academic Research. Introduction to Linux Quick Reference Guide. Research Computing Team V1.0

Linux Shell Script To Monitor Ftp Server Connection

Lecture 22 The Shell and Shell Scripting

CS 103 Lab Linux and Virtual Machines

File System Shell Guide

Introduction to Linux and Cluster Basics for the CCR General Computing Cluster

Automated Offsite Backup with rdiff-backup

INASP: Effective Network Management Workshops

Basic C Shell. helpdesk@stat.rice.edu. 11th August 2003

TEL2821/IS2150: INTRODUCTION TO SECURITY Lab: Operating Systems and Access Control

Backing Up TestTrack Native Project Databases

Introduction to Running Hadoop on the High Performance Clusters at the Center for Computational Research

Setting up PostgreSQL

Quick Introduction to HPSS at NERSC

Unix Guide. Logo Reproduction. School of Computing & Information Systems. Colours red and black on white backgroun

Submitting batch jobs Slurm on ecgate. Xavi Abellan User Support Section

Tutorial 0A Programming on the command line

Cleo Host Loginid Import Utility and Cleo Host Password Encryption Utility

Hadoop Basics with InfoSphere BigInsights

Secure Shell Demon setup under Windows XP / Windows Server 2003

Advanced Bash Scripting. Joshua Malone

sqlcmd -S.\SQLEXPRESS -Q "select name from sys.databases"

ICS 351: Today's plan

Step One: Installing Rsnapshot and Configuring SSH Keys

Outline. Unix shells Bourne-again Shell (bash) Interacting with bash Basic scripting References

UNIX, Shell Scripting and Perl Introduction

Installation Guide for WebSphere Application Server (WAS) and its Fix Packs on AIX V5.3L

Sophos Anti-Virus for Linux configuration guide. Product version: 9

Configuring MailArchiva with Insight Server

Creating Cost Recovery Layouts

CMSC 216 UNIX tutorial Fall 2010

Tutorial Guide to the IS Unix Service

MAX_RMAN_08137_IGNORE=5 DISK_RETENTION_POLICY='RECOVERY WINDOW OF 7 DAYS'

University of Toronto

Sophos Anti-Virus for Linux configuration guide. Product version: 9

Transcription:

28 Answers to Even-Numbered Exercises 1. Rewrite the journal script of Chapter 9 (question 5, page 340) by adding commands to verify that the user has write permission for a le named journal-le in the user s home directory, if such a le exists. The script should take appropriate actions if journal-le exists and the user es not have write permission to the le. Verify that the modied script works. 2. The special parameter "$@" is referenced twice in the out script (page 883). Explain what would be different if the parameter "$* " were used in its place. If you replace "$@" with "$*" in the out script, cat or less would be given a single argument: a list of all les you specied on the command line enclosed within single quotation marks. This list works when you specify a single lename. When you specify more than one le, the shell reports No such le or directory because there is not a le named the string you specied on the command line (the SPACEs are not special characters when they are enclosed within single quotation marks). 3. a lter that takes a list of les as input and outputs the basename (page 906) of each le in the list. 4. Write a function that takes a single lename as an argument and adds execute permission to the le for the user. $ function perms () { chmod u+x $1 a. When might such a function be useful? When you are writing many shell scripts, it can be tedious to give many chmod commands. This function speeds up the process. b. Revise the script so that it takes one or more lenames as arguments and adds execute permission for the user for each le argument. $ function perms { chmod u+x $* c. What can you to make the function available every time you log in? Put the function in ~/.bash_prole and/or ~/.bashrc to make it available each time you log in (using bash). 1

2 Answers to Even-Numbered Exercises d. Suppose that, in addition to having the function available on subsequent login sessions, you want to make the function available now in your current shell. How would you so? Use source to execute the le you put the function in, for example, $ source ~/.bash_prole 5. When might be necessary or advisable to write a script instead of a shell function? Give as many reasons as you can think of. 6. Write a shell script that displays the names of all directory les, but no other types of les, in the working directory. There are many ways to solve this problem. The listdirs script uses le to identify directory les and grep to pull them out of the list. Then sed removes everything from le s output, starting with the colon. $ cat listdirs le "$@" grep directory sed 's/:.*//' 7. Write a script to display the time every 15 seconds. Read the date man page and display the time, using the %r eld descriptor. Clear the winw (using the clear command) each time before you display the time. 8. Enter the following named saveles, and give yourself execute permission to the le: $ cat saveles #! /bin/bash echo "Saving les in current directory in le savethem." exec savethem for i in * echo "===================================================" echo "File: $i" echo "===================================================" cat "$i" ne a. What error message you get when you execute this script? Rewrite the script so that the error es not occur, making sure the output still goes to savethem. You get the following error message: cat: savethem: input le is output le Add the following lines after the line with on it: if [ $i == "savethem" ] ; continue b. What might be a problem with running this script twice in the same directory? Discuss a solution to this problem. Each time you run saveles, it overwrites the savethem le with the current contents of the working directory. When you remove a le and run saveles again, that le will no longer be in savethem. If you want to

Answers to Even-Numbered Exercises 3 keep an archive of les in the working directory, you need to save the les to a new le each time you run saveles. If you prex the lename savethem with $$, you will have a unique lename each time you run saveles. 9. Read the bash man or info page, try some experiments, and answer the following questions: 10. Using the nd utility, perform the following tasks: a. List all les in the working directory and all subdirectories that have been modied within the last day. $ nd. -mtime -1 b. List all les that you have read access to on the system that are larger than 1 megabyte. $ nd / -size +1024k c. Remove all les named core from the directory structure rooted at your home directory. $ nd ~ -name core -exec rm {} \; d. List the inode numbers of all les in the working directory whose lenames end in.c. $ nd. -name "*.c" -ls e. List all les that you have read access to on the root lesystem that have been modied in the last 30 days. $ nd / -xdev -mtime -30 11. a short script that tells you whether the permissions for two les, whose names are given as arguments to the script, are identical. If the permissions for the two les are identical, output the common permission eld. Otherwise, output each lename followed by its permission eld. (Hint: Try using the cut utility.) 12. Write a script that takes the name of a directory as an argument and searches the le hierarchy rooted at that directory for zero-length les. Write the names of all zero-length les to standard output. If there is no option on the command line, have the script delete the le after displaying its name, asking the user for conrmation, and receiving positive conrmation. A f (force) option on the command line indicates that the script should display the lename but not ask for conrmation before deleting the le. The following script segment deletes only ordinary les, not directories. As always, you must specify a shell and check arguments. $ cat zerdel if [ "$1" == "-f" ] nd $2 -empty -print -exec rm -f {} \; else nd $1 -empty -ok rm -f {} \; 13. Write a script that takes a colon-separated list of items and outputs the items, one per line, to standard output (without the colons).

4 Answers to Even-Numbered Exercises 14. Generalize the script written in exercise 13 so that the character separating the list items is given as an argument to the function. If this argument is absent, the separator should default to a colon. This script segment takes an optional option in the form dx to specify the delimiter x: $ cat nodel if [[ $1 == -d? ]] del=$(echo $1 cut -b3) shift else del=: IFS=$del set $* for i echo $i ne 15. Write FUNPATH. a function Assume named that funload the format that of takes FUNPATH as its single is the argument same as PATH the name and of that a le searching containing FUNPATH other functions. is similar The to the purpose shell s of search funload of the is to PATH make variable. all functions in the named le available in the current shell; that is, funload loads the functions from the named le. To locate the le, funload searches the colon-separated list of directories given by the environment variable 16. Rewrite bundle (page 910) so that the script it creates takes an optional list of lenames as arguments. If one or more lenames are given on the command line, only those les should be re-created; otherwise, all les in the shell archive should be re-created. For example, suppose that all les with the lename extension.c are bundled into an archive named srcshell, and you want to unbundle just the les test1.c and test2.c. The following command will unbundle just these two les: $ bash srcshell test1.c test2.c $ cat bundle2 #!/bin/bash # bundle: group les into distribution package echo "# To unbundle, bash this le" for i echo 'if echo $* grep -q' $i ' [ $# = 0 ]' echo echo "echo $i 1&2" echo "cat $i <<'End of $i'" cat $i echo "End of $i" echo ne 17. What kind of links will the lnks script (page 886) not nd? Why? 18. In principle, recursion is never necessary. It can always be replaced by an iterative construct, such as while or until. Rewrite makepath (page 950) as a nonrecursive function. Which version you prefer? Why?

Answers to Even-Numbered Exercises 5 function makepath2() { wd=$(pwd) pathname=$1 while [[ $pathname = */* && ${#pathname} 0 ]] if [[! -d $pathname ]] mkdir "${pathname%%/*}" cd "${pathname%%/*}" pathname="${pathname#*/}" ne if [[! -d $pathname && ${#pathname} 0 ]] mkdir $pathname cd $wd } The recursive version is simpler: There is no need to keep track of the working directory and you not have to handle making the nal directory separately. 19. Lists are commonly stored in environment variables by putting a colon (:) between each of the list elements. (The value of the PATH variable is a good example.) You can add an element such a list by catenating the new element to the front of the list, as in 20. Write a function that takes a directory name as an argument and writes to standard output the maximum of the lengths of all lenames in that directory. If the function s argument is not a directory name, write an error message to standard output and exit with nonzero status. $ function maxfn () { typeset -i max thisone if [! -d "$1" -o $# = 0 ] echo "Usage: maxfn dirname" return 1 max=0 for fn in $(/bin/ls $1) thisone=${#fn} if [ $thisone -gt $max ] max=$thisone ne echo "Longest lename is $max characters." 21. Modify the function you wrote for exercise 20 to descend all subdirectories of the named directory recursively and to nd the maximum length of any lename in that hierarchy. 22. Write a function that lists the number of ordinary les, directories, block special les, character special les, FIFOs, and symbolic links in the working directory. Do this in two different ways:

6 Answers to Even-Numbered Exercises a. Use the rst letter of the output of ls l to determine a le s type. $ function ft () { typeset -i ord=0 dir=0 blk=0 char=0 fo=0 symlnk=0 other=0 for fn in * case $(ls -ld "$fn" cut -b1) in d) ((dir=$dir+1)) b) ((blk=$blk+1)) c) ((char=$char+1)) p) ((fo=$fo+1)) l) ((symlnk=$symlnk+1)) a-z) ((other=other+1)) *) ((ord=ord+1)) esac ne echo $ord ordinary echo $dir directory echo $blk block echo $char character echo $fo FIFO echo $symlnk symbolic link echo $other other

Answers to Even-Numbered Exercises 7 b. Use the le type condition tests of the [[ expression ]] syntax to determine a le s type. $ function ft2 () { typeset -i ord=0 dir=0 blk=0 char=0 fo=0 symlnk=0 other=0 for fn in * if [[ -h $fn ]] ((symlnk=$symlnk+1)) elif [[ -f $fn ]] ((ord=ord+1)) elif [[ -d $fn ]] ((dir=$dir+1)) elif [[ -b $fn ]] ((blk=$blk+1)) elif [[ -c $fn ]] ((char=$char+1)) elif [[ -p $fn ]] ((fo=$fo+1)) else ((other=other+1)) ne echo $ord ordinary echo $dir directory echo $blk block echo $char character echo $fo FIFO echo $symlnk symbolic link echo $other other 23. Modify the quiz program (page 956) so that the choices for a question are ranmly arranged.