Вы находитесь на странице: 1из 76

Chapter 9

Utilities

© Amplify Mindware Pvt. Ltd


The init Daemon
 Who activates the daemons ?

 init , the first process created during boot, is responsible for activating the
daemons. init makes use of the files: rc and rc.local

init /etc/rc

cron /var/spool/cron/crontabs

at /var/spool/cron/at*

© Amplify Mindware Pvt. Ltd


Time Utilities - at
 The command at executes a command(s) or shell script(s) at a specified time. The
result is sent by mail to the user if no redirection has been performed.

 % at 1:00
at> tar cvf /dev/rst8
 % at 13:07
at> batchfile
 % at 0815 Jan 24
at> who_is_on > who_was
 % at now+1 day
at> make_proj big-project-file
 % at 5 pm Friday
at> echo Backup for `date` started
at> backup_files all

 On some systems use this format: % at time shell_script


% at midnight backup_script
© Amplify Mindware Pvt. Ltd
at – cont’d
-m Send mail to the user if the command is completed successfully.

-r Remove a command from the queue according to its number.


-d -d instead of –r on some systems.

-l Display the list of commands in the queue.

-c C shell (csh) is used to execute script


Doesn’t exist on some systems.

-s Standard (Bourne) shell (sh) is used to execute the job. By default, the
SHELL environment variable determines which shell to use.
Doesn’t exist on some systems.

© Amplify Mindware Pvt. Ltd


Time Utilities - atq, atrm
 atq
The command atq displays information about the commands in queue for
execution by the command at (Same as at –l).

 Options: [Not available on some systems]

-c Sort commands by time of delivery to the queue.


-n Number of commands in the queue.
 atrm
The command atrm removes commands from the queue
(Same as at –r or at –d).
 Options: [Not available on some systems]

-i Asks for confirmation before removing a command from the queue.


-n Removes all of the current user’s commands from the queue.

© Amplify Mindware Pvt. Ltd


Time Utilities - crontab
 Only root can access the crontab files directly. There is a crontab command
that enables users to add their own commands for execution.

 The command crontab is used to execute commands or files at a fixed time.


In contrast to at, which is normally used for a single execution of a command,
crontab is used for commands which must be executed repeatedly

 Options for the command crontab

-e Puts users into an editor, where they can edit their file
/var/spool/cron/crontabs/username
-l (list) Displays the user’s file, if it exists.
-r (remove) Removes the user’s file.
-d -d instead of –r on some systems.

© Amplify Mindware Pvt. Ltd


crontab – cont’d
 Maintenance of the crontab file:

crontab -e

vi /tmp/.... When running crontab -e

Addition/deletion of lines
in the private database

:wq /var/spool/cron/crontabs/user
 Structure of the crontab file collection of lines:
minutes hours day-of-month month day-of-week
command
© Amplify Mindware Pvt. Ltd
crontab – cont’d
Field Format Example Meaning
Number 0 12 1 1 * new_year Will run at 12:00 on New
Year
Asterisk 30 * * * 1 MonProg Will run hourly, on the half
hour, on Mondays
set of numbers 0 0 * 4,6,9,11 * prog2 Will run daily at 00:00 in
months with 30 days
range of 0 8-16 * * * users Will run throughout work
numbers hours, on the hour

© Amplify Mindware Pvt. Ltd


cc - Introduction
 C is the natural language for program development in the UNIX environment.
The standard compiler is cc.

 The cc compiler runs other commands to do the job:


cpp - C preprocessor
ccom - C compiler
as - assembler
ld - link editor

 As in all compilers in UNIX, the default name of the execution file created by
compilation is a.out.

 The compiler generally operates on files with the extension “.c”. cc can also be
run on assembler files (extension “.s”) and on object files (extension “.o”).

 Temporary files are stored in /tmp.

© Amplify Mindware Pvt. Ltd


cc – Example – cont’d
For example
% ls ->prog.c
% cc prog.c
% ls -> a.out prog.c
% cc –o prog prog.c
% ls -> a.out prog prog.c

 Options:
-o file Changes the name of the execution file created from a.out to file.
-O Optimized compilation.
-g Creates a symbol table for debugging.
-c Skips stage ld in the compilation. This option is used to compile
program modules. The output is a file of the same name with the
extension “.o”.

© Amplify Mindware Pvt. Ltd


cc – Additional Examples
% ls
part1.c part2.c
% cc -c part1.c
% cc -c part2.c
% ls
part1.c part1.o part2.c part2.o
% cc -o myprog part1.o part2.o

 myprog is ready to run.

 Assuming a change in part1.c:


% cc –o myprog part1.c part2.o

 myprog is ready to run. There is no need to recompile part2.c since no


change was made in it.

© Amplify Mindware Pvt. Ltd


su
 Substitute User:

 This command is used to temporarily replace the user on a given terminal.

 After the command is executed, the new user can work at the terminal, but the
working environment remains unchanged.

 The shell (csh/sh) run for the new user is not a login shell, and therefore the
.login (.profile) file is not executed. The .cshrc file (in the case of the
csh) is executed.

 su prompts the new user for a password as if login was being performed.

© Amplify Mindware Pvt. Ltd


su – cont’d
 Options:

%su - username
 Executes a full user substitution including running the login file.

% su -f username
[On some systems: % su username –f ]
 Does not execute the .cshrc file for csh.

% su username -c command
 Switches to a new user in order to execute the command. Then returns to the
original user.

© Amplify Mindware Pvt. Ltd


su – cont’d
 Super User:

 su without arguments means switch to user root.

 On some systems - If the group wheel in the file /etc/group does not contain
an empty list, only the users listed there are permitted to execute su to root,
even if unlisted users know the root password.

 Exercise:
 Try executing su to user root. Were you prompted to enter the root
password?

© Amplify Mindware Pvt. Ltd


How to Return From su
 There are two options for returning from the command su:

 Type the command exit in the new user shell. The user terminates the
shell and reverts to the first user.

 suspend suspends the shell of the new user without killing the process.

 Recall that suspend is equivalent to Ctrl-z for the new user's shell.

 After suspend, return to the new shell is by the fg command.

© Amplify Mindware Pvt. Ltd


File Comparison - cmp
There are a number of commands for file comparison.

 cmp
This command compares two files, byte by byte, and reports the first occurrence
of a different byte.
 This command can be used for comparing binary files.

 Option:

% cmp -l f1 f2

 Gives all the differences between the files. The output includes the ordinal
number of each byte that is different and the octal value of the bytes that
are different.

© Amplify Mindware Pvt. Ltd


cmp – cont’d
 Example f1 f2
This is the This is the
% cmp f1 f2 first file second file
f1 f2 differ : char 13, line 2

% cmp -l f1 f2
13 146 163
14 151 145
15 162 143
16 163 157
17 164 156
18 40 144
19 146 40
20 151 146
21 154 151
22 145 154
23 56 145
24 12 56
cmp: EOF on f1
%

© Amplify Mindware Pvt. Ltd


File Comparison - comm
 This command compares two files and can report:
 Lines that exist in the first file only.
 Lines that exist in the second file only.
 Lines that exist in both files.

 By default, the command reports about the three above groups in three
columns.

 Options:
% comm -1 f1 f2
 Drop column 1 from the output (lines in the first file only).

% comm -12 f1 f2
 Display column 3 only (lines in both files).

© Amplify Mindware Pvt. Ltd


comm - example
mickey 2: comm f3 f4
first line
second line
second line is a bit longer
third
third line
mickey 3: comm -1 f3 f4
first line
second line is a bit longer
third
mickey 4: comm -2 f3 f4
first line
second line
third line
mickey 5: comm -3 f3 f4
second line
second line is a bit longer
third
third line
mickey 6: comm -12 f3 f4
first line

© Amplify Mindware Pvt. Ltd


comm - example – cont’d
mickey 7: comm -13 f3 f4
second line is a bit longer
third
mickey 8: comm -23 f3 f4
second line
third line
mickey 9: comm -123 f3 f4
mickey 10: comm f3 f4 | sort
first line
second line is a bit longer
third
second line
third line
mickey 11:

© Amplify Mindware Pvt. Ltd


File Comparison - diff
 The command diff is the most powerful of the commands for comparing text
files.

 The output is the different lines and the change required to make the files
identical.

% diff f1 f2
 Compares files f1 f2.

% diff d1 d2
 Compares files of the same name in subdirectories d1 d2.

© Amplify Mindware Pvt. Ltd


script
 The command script is used to save everything happening on the screen, in a file.

 This command opens a new file named typescript, in which anything appearing on
the screen will be saved.

 Terminate the command by calling exit.

% script filename
 Replaces typescript with filename

% script -a [filename]
 Append anything displayed on the screen to the existing typescript file.

© Amplify Mindware Pvt. Ltd


file
 The command file identifies file types.
 The file types which can be identified are:
File name message
code sparc pure dynamically linked executable
code.c c program text
counts ascii text
empty empty
libz.a archive random library
memos directory
project symbolic link to /usr/project
script executable shell script
calc.exe DOS executable (EXE)
 Exercise :
 What types of files do you have in your home directory?
© Amplify Mindware Pvt. Ltd
bc
 A friendly front-end to the dc calculator utility.

 A calculator that uses a simple C-like “language” for calculating and interpreting
expressions.

 Capable of calculating expressions with the power of C.

 Examples:
23*(90+78.88)
3884.24
sqrt(90)
9.4868...
s(3.14)
0.00159
a=e(c(0.25))
a
2.635
© Amplify Mindware Pvt. Ltd
bc – cont’d
 Additional structures:
define, for, while, if

 Functions: (to use this functions add the –l option to bc)


l - log; e - exponent; c - cosine;
s - sine; j(n,x) - bessel; a – arctan

 For decimal fractions uses the command scale:


% bc
22/7
3
scale=44
22/7
3.14285714285714285714285714285714285714285714

© Amplify Mindware Pvt. Ltd


whatis
 % whatis cp cp (1)-copy files

Command description
Command name
in the manual
The section in the
manual containing
the command

 The command whatis is used when we know the command we want to check -
unlike cases when we do not remember the exact name (in which case we use
the command
man -k copy).

© Amplify Mindware Pvt. Ltd


Information About Users
 w - Reports on who is doing what in the system.
 % w
2:17pm up 37 days, 9 users, load average: 0.05, 0.00, 0.00
USER TTY LOGIN@ IDLE JCPU PCPU WHAT
eric ttyp0 1:09pm 54 1 -tcsh
elena ttyp1 7:40am 2 4:18 3 -tcsh
eddie ttyp2 12:43pm 1:32 1 -tcsh
anna ttyp3 9:02am 5 elm
jerry ttyp4 8:57am 7 5 1 elm
beni ttyp5 10:52am 13 46 3 -csh
barak ttyp6 11:22am 23 35 4 -tcsh
barak ttyp7 11:47am 27 7 1 -tcsh
yitzy ttyp9 2:17pm 1 w

 On some systems tty’s are designated pts/ instead of ttyp .


 Some versions add the column FROM (host that the user logged in from).

© Amplify Mindware Pvt. Ltd


Information About Users – cont’d
 who - Reports on who is logged onto the system.

% who
joanne ttyp0 Sep 12 13:09 (212.32.122.11)
sujin ttyp1 Sep 12 07:40 (62.33.26.130.myISP1.net)
eddie ttyp2 Sep 12 12:43 (62.33.26.132.myISP1.net)
anna ttyp3 Sep 12 09:02 (anna)
jerry ttyp4 Sep 12 08:57 (localhost.locald)
benny ttyp5 Sep 12 10:52 (indy5:0.0)
ho ttyp6 Sep 12 11:22 (star.com)
kareem ttyp7 Sep 12 11:47 (aloha)
yitzy ttyp9 Sep 12 14:17 (minney)

© Amplify Mindware Pvt. Ltd


Information About Users
% who am i

caro ttyp1 Aug 4 08:40 (office239)

user name terminal login time Computer name


 who am i display the user name that opened a login shell.

% whoami user name


Limori

 whoami display the user name that opened the current shell.

© Amplify Mindware Pvt. Ltd


id
 The id command gives identification information about the current
user.

%id
uid=279(alon) gid=104(eng)
groups=104(eng),42(sela),114(database),123(mahonadm),
134(commando)

© Amplify Mindware Pvt. Ltd


Information about Processes
 ps lists current processes belonging to you or specified user(s).
 % ps –ef
 % ps –ax

pid tt STATE TIME COMMAND


0 ? D 0:27 swapper
1 ? IW 0:02 /sbin/init -
2 ? D 0:02 pagedaemon
55 ? IW 0:01 portmap

157 ? IW 0:00 cron


162 ? IW 0:02 inetd
827 ? IW 0:33 in.telnetd
1319 ? IW 0:00 in.rshd
1321 co IW 0:00 tcsh -c
1322 co R 0:00 ps -ax

© Amplify Mindware Pvt. Ltd


Exercises
In this exercise we will learn to use some widely used utilities for dealing with text
and ascii files. A sound knowledge of these utilities will increase your productivity,
and it is therefore very important that you take the time to complete this exercise.
To successfully complete this exercise, you will have to use the on-line UNIX
manuals. This way you will be able to learn the correct format of the parameters for
the different commands (beyond what appears in the slide printouts). The required
answer to every question is a single command, or a number of commands
connected by means of a pipe (|) or a semi colon. For example:
The answer to the question “How can we print a list of files containing the word
hello?”
would be
lpr `egrep -l hello *.c`
In the course of the exercise you will be referred to a number of files. These files
are located in a directory named dir_ex2 under your home directory in this course.
Now enter that directory.
Examine each answer carefully, and write down the answers.

© Amplify Mindware Pvt. Ltd


Exercises – cont’d
1. Let's return to the command ls -s. This command prints the names of the files in
the directory and their sizes. If we sort them by size, we will find the largest file.
Write a sequence of commands linked with a pipe which will display the three
largest files in the current directory.
Answer

2. Try the command df without arguments. What does it display?


Correct, the command displays all the file systems comprising our tree.
What does the command df display when we transfer the name of a file to it as an
argument?

Answer

Find file system which occupied the most disk space. The result should be a single
line showing the status of this file system.
Answer

© Amplify Mindware Pvt. Ltd


Exercises – cont’d
3. Let's recap the command who, which displays the current users in the system.
Use it to check how many users are logged onto the system (output is the number
of users).
Answer
How many are working on editing (running “vi” or “emacs”)?
Answer
4. Let's recall some of the elements of the command grep. Remember that the
syntax of this command is different from that of the shell with regard to the
meaning of special characters in regular expressions: thus, “*” means zero or more
instances of the character preceding it, while “+” (egrep) means one or more
instances of the character preceding it.
Therefore, if we wish to display the names of the files in the present working
directory whose name is made of letters or an underscore only, we write the
command:

Answer

© Amplify Mindware Pvt. Ltd


Exercises - cont'd
Now display the line numbers (one of the options of grep) as well as the lines of a
given file which contain the string ***hello*** (note that the asterisks are
obligatory in the search). Test yourself on the hello file, which contains numerous
instances of the string hello, only two of which comply with the specified criteria.

Answer

5. Display all the lines which have five characters or more in a given file; try your
solution on file less_than_five .

Answer

© Amplify Mindware Pvt. Ltd


Exercises - cont'd
We wish now to display all the lines in a given file which contain less than five
characters. Remember the option -v. This displays all the lines which do not contain
the string we are looking for. Try your solution on file less_than_five .
Answer
6. One of the options of grep is to count the number of lines which contain an
instances of a specified string in a file. Use this option and write a sequence of
commands which will identify and display the name of the file which has the largest
number of lines containing the string HELLO. Test your solution on files: hello1,
hello2, hello3.
Answer
7. Most of the commands in UNIX can accept more than one file as argument. For
instance, the command sort file1 file2 will sort both files.
Use this feature to display the list of files in any two directories.

Answer

© Amplify Mindware Pvt. Ltd


Exercises - cont'd
Now display the list of files with identical names in two given directories
(disregarding their content, links between them etc.). To do so, create a directory
named test-dir as a sub-directory of ex_dir2 and place two files named hello and
empty in it, as well as two files named yes and not. Test your answer on these
directories.
Answer

Answer

Following this, display a list of files located in one of the directories, ex_dir2 and
test-dir but not in both.

Answer

© Amplify Mindware Pvt. Ltd


Exercises - cont'd
8. The command find is a very powerful command. It operates on an entire sub-
tree, finds the files fulfilling certain specified criteria, and performs an action on the
files it found.
For instance: find ~ -name ”*.o” -print
This command finds all the files from the home directory down, checks if they fulfill
the name criterion (filename extension “.o”) and prints their name.
Use this command to create a report on all the files in a given sub-tree which
belong to specified users and groups. Check which files in directory /usr/bin
belong to root and to group bin.
Answer

9. Create a list of files in a given directory tree which have not been modified
during the last 7 days. Test your solution on the directory /etc.

Answer

© Amplify Mindware Pvt. Ltd


Exercises - cont'd
10. Let's examine the option -exec of the find command. This option enables us
to execute commands on the files found. For instance:
find ~ -mtime +30 -print -exec rm -i “{}” \;
What does this command do?
Correct, it finds all the files from the home directory down which were not modified
during the last 30 days, prints their name, and deletes them with a simple rm
command.

Write a command which finds all the files from your home directory down which
were accessed during the last 7 days, and displays their content on the screen.

Answer

© Amplify Mindware Pvt. Ltd


Exercises - cont'd
11. The command du displays information on the space which directories and files
occupy on the disk. It works recursively on all the directories in the sub-tree. Display
the space taken by your home directory without a breakdown by sub-directories (the
total space only - one of the options of du).

Answer

Now display the same information broken down by sub-directories.

Answer

© Amplify Mindware Pvt. Ltd


Exercises - cont'd
12. The command tar works on archives. That means we can create an archive
which will contain information on a given sub-tree - both on the contents of the
files in the sub-tree and on the links between the directories.
Place yourself in your home directory. Now create an archive of the sub-tree from
directory ex_dir2 down, and name it arch.tar

Answer

© Amplify Mindware Pvt. Ltd


Exercises - cont'd
We can now open the archive and recover the sub-tree represented there. Create a
sub-directory named dirarch as a subdirectory to your home directory. Open in it the
archive file you have created in your previous task. Check that you got the original
sub-tree you saved.
Answer

13. Write a list of commands that will display only the digits from the output of the
command date.
Answer

14. Write a list of commands that will print information about all of your sub-
directories, and count them.
Answer

© Amplify Mindware Pvt. Ltd


Chapter 10

Working with csh

© Amplify Mindware Pvt. Ltd


Variables - Why?
 To save special values used by the csh.

 Variables make it possible to create a convenient and flexible working


environment suited to the program's needs.

 To shorten commands, thus avoiding unnecessary keyboard work.

 Used in shell scripts.

© Amplify Mindware Pvt. Ltd


Variables
 csh supports the definition and use of variables.

 A variable can contain a single value or a list of values.

 csh stores a list of variables, at all times, which can be referred to and
used.

 There are some variables with predefined names, which fulfill specific
functions.

© Amplify Mindware Pvt. Ltd


Assigning Values to Variables
 To assign a value to a variable the set command is used.
 The command can be used to assign a single value or a list of values.

 Examples:
% set name = Yitzy
% echo $name
Yitzy
% set names = ( Yitzy Alon )
% echo $names
Yitzy Alon

 Exercise:
 Assign a list of values to a variable without using parenthesis and
see what you© get.
Amplify Mindware Pvt. Ltd
Variable Substitution
 The $ sign preceding a variable name causes the csh to replace the
variable name with its content.

% set name = iris


% echo $name
iris

 The $# signs preceding a variable name causes the shell to replace the
variable with the number of elements in the variable.
 % set names = ( iris victor )
% echo $#names
2

© Amplify Mindware Pvt. Ltd


Variable Indexing: [ ]
 Using the square brackets [ ] cause the shell to substitute a single value or a
range of values.

 Indexing Options:
$var[index] The value in the index entry.
$var[-index] The values up to the index entry.
$var[from-] The values from the index entry.
$var[from–to] The values between from and to.

 Examples:
% set a = (a b c d e f)
% echo $a[2]
b
% echo $a[-2]
a b
% echo $a[4-6]
d e f
© Amplify Mindware Pvt. Ltd
Delimiting Variable Names: { }
 Using curly brackets { }

% set prefix = X
% cat ${prefix}files
The truth is out there … somewhere!

 Exercise:
 Run the previous commands in your ~/class directory without the
{} brackets and see what you get. Explain what you see!!

© Amplify Mindware Pvt. Ltd


Back Quote
 The back-quote is used to execute a sub-command
% command `sub command`
 The back-quote instructs the shell to:
 Execute the sub-command.
 Replace the command on the command line with its output
(to serve as command line arguments for the primary command).
 The sub-command is used mainly:
 To insert a command’s output into a variable.
% set x = (`cat file_1`)
 To prepare command line arguments for the primary command.
% lpr `egrep -l important *trash*`
 Note the difference:
% egrep -l important *trash* | lpr

© Amplify Mindware Pvt. Ltd


Additional Examples
 The grep command prepares a list of files containing the word salary, which the
cat command then prints to the standard output.
% cat `grep -l salary *`

 Show the largest file.

% set x = (` ls -s | sort -n | tail -1` )

List of files Sort the list Display only


with size the last and
largest file
x = (12345 bigfile)
% cat $x[2]

© Amplify Mindware Pvt. Ltd


Exercise
%set name = Sylvia
%set address = (653 24th St., San Francisco)
%set phone = 7515141
%set card = ($name $address $phone)
%echo I, $name, live at $address
%echo My phone# is 415-$phone
%echo $card
%echo ${name}Jones

1. What will be displayed on the screen?


2. The variable "path" has three values (for instance /usr/ucb, /bin,
/usr/local/bin). Write a command that will add the directory
/usr/games at the head of the list and another command which will add
/usr/games at the third place in "path".
Summarize your conclusions from the exercise.
© Amplify Mindware Pvt. Ltd
Variables with Fixed and
Known Names
 Their default value is assigned at login.

 The value can be changed - but proceed with caution.

 A list of all the defined variables and their values are obtained by means of the
command set.

 Important examples:

 home or ~ Contains our login directory, to which we


return by means of the command cd.
 history Number of saved commands.
 path The directories in which the shell searches
for commands to execute(binary
executables and scripts).

© Amplify Mindware Pvt. Ltd


Variables with Fixed and
Known Names – cont’d
 cwd Current working directory.

 cdpath When writing the command cd directory, this


variable provides a search path for that directory.

 prompt Your prompt. A process in which this variable is


not initialized is a non-interactive process.

© Amplify Mindware Pvt. Ltd


Example of the Use of
"Constant" Variables
% alias cd ’ cd \!* ; set prompt = "$cwd : “ ’

Goes to the Insert a new value The new value of


required in the variable the prompt is the
directory “prompt” new directory

© Amplify Mindware Pvt. Ltd


The Variable "status"
 The variable status contains the exit status of the last command.

 Example:

grep string file >& /dev/null


if ($status == 0) then
echo string is in file
endif

 A value of zero signifies success otherwise failure.

© Amplify Mindware Pvt. Ltd


Environment Variables
 csh also maintains a list of environment variables.

 Environment variables are regarded as ordinary variables. The main


difference is that they are assigned a value with the setenv
command.

 It is customary to write the names of environment variables in upper


case letters.

 Environment variables are duplicated when child processes are created,


whereas ordinary variables are not.

 Some of the ordinary variables (user, cwd, path) are duplicated as


environment variables during csh initialization.
© Amplify Mindware Pvt. Ltd
set vs. setenv
ACTION SET SETENV

Assign a value to a set x=abc setenv X abc


variable

Assign a value to a set x=(a b c) No array of


vector environment variables

View the value of a echo $x echo $X


variable

View all variables Set env, setenv

Cancel a variable unset x unsetenv X

Duplication for child NO YES


process

© Amplify Mindware Pvt. Ltd


Chapter 11

ksh

© Amplify Mindware Pvt. Ltd


ksh
 Working with ksh is quite similar to csh except for several differences.

 The differences between “csh” and “ksh” are:


 Meta Characters.
 Options.
 Command’s history.
 aliases.

© Amplify Mindware Pvt. Ltd


The Interpretation Mechanism
 The ksh has special characters (Meta Characters) which have special
meaning for the shell.

 The ksh interprets these characters BEFORE executing a command.

 Example:
 $ ls *.o

 The command ls does not know the meaning of the “*o” argument.
The shell interprets the “*.o” to be the list of files that end with “.o”,
and passes this list as arguments to the ls command.

© Amplify Mindware Pvt. Ltd


Meta Characters
 The basic ksh pattern matching characters:

 Asterisk *
 Matches all strings (including an empty string)
 Question mark ?
 Matches one character only
 Squared brackets [ ]
 Matches on character of the set in brackets.

© Amplify Mindware Pvt. Ltd


Meta Characters
 ksh provides more pattern matching characters than csh.

 Examine the following:

$ ls
xy ab abcbcx abcx
abx acx xaabby xaby

 *(pattern)  match zero or more instances of any pattern. For


example:

$ ls x*(ab)y
xy xaby

© Amplify Mindware Pvt. Ltd


Meta Characters
 +(pattern)  match one or more instances of any pattern. For example:

$ ls x+(ab)y
xaby xababy

 ([expression])  the pattern itself can be a complex expression. For example:

$ ls a*([bc])x
abx acx abcx abcbcx

© Amplify Mindware Pvt. Ltd


Meta Characters
 ?(pattern)  match zero or one occurrence of a string matching pattern.

 !(pattern)  matches anything that does not match a pattern.

 @(pattern_1 | pattern_2 | … | pattern_n)  matches anything that


matches pattern_1 … pattern_n

© Amplify Mindware Pvt. Ltd


Meta Characters
 When ksh cannot match a file to a given pattern, it will ignore the meta
character, and use it as a string.

$ echo *a
a aba abba
$ echo *aa
*aa

© Amplify Mindware Pvt. Ltd


Exercise
 Display all files beginning with a ‘c’, followed be zero or more ‘o’s and ending
with any character/s.

 Display all file name’s containing only lower case letters.

© Amplify Mindware Pvt. Ltd


Redirection
 Input from a file by means of <:

$ command < file.dat

 Standard output redirected to a file by means of > (creates a new file) and >>
(appends to a file):

$ command > file.out


$ command >> file.out
$ ls –l > files

 Standard error messages redirected by means of 2> :

$ cat exist notexist 2> err_file

 Standard error messages appended to a file 2>> :


cat exist notexist 2>> err_file

© Amplify Mindware Pvt. Ltd


Redirection in sh, bash, ksh
 ksh permits simultaneous separate redirection of the output and the errors as
follows:
 $ command < infile > outfile 2> errfile

input file - stdin

output file - stdout

errors file - stderr


 $ command >> addfile 2>> errfile < infile

output file - stdout

input file - stdin

errors file - stderr


© Amplify Mindware Pvt. Ltd
How to Avoid Mistakes?
$ command > file

 If the file exists, ksh will truncate it.

 This is an irreversible action. In order to avoid such behavior use the following
command:

$ set –o noclobber

 We can cancel this command by typing

$ set +o noclobber

© Amplify Mindware Pvt. Ltd


History
 The ksh has the fc internal command which allows users to view and edit
commands executed at the current or previous login session.

 All the commands are stored in a file.

 The HISTFILE variable contains the name of the file (by default .sh_history).

 The HISTSIZE variable contains the maximum number of commands stored in


the history file (default – 128 commands).

 The history command is a shell alias for fc –l

© Amplify Mindware Pvt. Ltd


History
 In order to view history commands users can user the fc command with the –l
option:
$ fc –l [# First Command] [# Last Command]
 For Example:
$ fc -l 2 4
2 clear
3 ls -l ksh
4 which ksh

 In order to edit / execute the N last commands users can user the fc command:
$ fc <# First Command> <# Last Command>

 This command will open the standard editor window (depending on the variable
FCEDIT). When quitting the editor, all the commands currently displayed in the
editor window will be executed.

© Amplify Mindware Pvt. Ltd


Command Line Editing
 ksh gives the ability to choose two ways of line editing:

 Edit mode vi – edit the line as in the vi editor. <esc> key, move to
escape-mode. In escape mode, the line up/down keys (k, j) move
through the history.

 Edit mode emacs – edit the line as in the emacs editor, the line
up/down keys (Ctrl-p , Ctrl-n) move through the history.

 To change edit mode use:


 set –o vi for vi.
 set –o emacs for emacs.

© Amplify Mindware Pvt. Ltd


alias
 alias is a tool by which users can define shortcuts to common commands.

 ksh aliases mechanism is similar to the csh’s aliases though it:


 Has different syntax.
 Has some additional features.
 Doesn’t allow arguments. The solution for this issue will be discussed
later in the course (functions).

 Syntax:
alias <name>=<command>
 For example:

alias h=history
alias ll=“ls –l”

© Amplify Mindware Pvt. Ltd


Exercise
 Use wildcards to find files according to the following criteria. Check yourself by
executing the commands on the “wildcards” directory supplied.
 Find all files named with only uppercase letters and have even number of
characters (for example “AA”).
 Find all files named with an odd number of letters (for example “aaa”).
 Find all files named in the following order:
 One or more “a”

 One or more “b”

 One or more “c”

 For example: “abbcccc”


 Print the inode number of the biggest file found in the last exercise.

© Amplify Mindware Pvt. Ltd


Exercise – cont’d

 Find all file names which a lower case letter between two upper case
letters.

 What is the command that will display the following files:


AaaA AaabbbbnnnnA AbbMNhhT

 History:

 Set the variable HISTSIZE with the number of the last command you want
to save.
 Set the HISTFILE to .my_sh_history
 Display your previous typed commands.

© Amplify Mindware Pvt. Ltd

Вам также может понравиться