











Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!












ECS 40 UNIX Lecture Notes I. UNIX commands you should already know. A. cd [directoryName] Change directory. B. pwd List current working directory. C. • cp sourceFilename destinationFileName Copies a file. D. cp { sourceFilename}+ destinationDirectory Copies file(s) into a directory. E. mv oldFileName newFileName Renames a file or directory. F. mv {fileName}+ directoryName Moves listed files into the directory. G. mkdir {directoryName}+ Creates directory(s). H. rm –irf {fileName}* Removes file(s). -i = prompts. –r = recursively. –f inhibit prompts. I. rmdir {directoryName}+ J. cat {fileName}* List contents of file(s). K. more {fileName}* List contents of files(s) one screen at a time. L. lpr –h [-P printerName ] {fileName}+ Prints file(s). –h = without header page. M. chmod –R change {fileName}+ Changes permissions of file(s). –R = recursively. Change can be an octal or of the form cluster [+-=] permissions , where cluster can be u (user) , g (group), o (others), or a (all); and permissions can be r (read), w (write), or x (execute). II. Simple UNIX utilities A. head –n { fileName}* Displays the first n lines of file(s). If no n , then it defaults to 10. B. tail –n { fileName}* Displays the last n lines of files(s). If no n, then it defaults to 10. C. wc –lwc { fileName}* Counts the number of lines (-l), words (-w), and/or characters (-c) of files(s). D. ls –alR {filename}* {directoryName}* Lists information about files. –a = all files including those beginning with a period. –l = long format for each file. –R = recursively list contents of directory(s). E. sort -tc -r [+ startSortField [ -lastSortField ]] { fileName}* = Sorts a file in ascending or descending order. p. 224
1. -tc = specify field separator c instead of white spaces. 2. -r = descending order. 3. Sort field numbering starts at zero. •If no lastSortField , then all fields following the startSortField are used for sorting. 4. sort –t, -r +2 –4 test.csv will sort the lines of test.csv in descending order based on the 3rd^ through 4th^ fields which are separated by commas. III. Regular expressions used in grep, awk, sed, and vi. A.. = single character. In filename substitution this a "?" B. [..] = any single character in the bracket. C. * = zero or more D. ^ = beginning of line. E. $ = end of line F. \ = The meaning of a metacharacter is inhibited. G. Extended regular expressions. Used by awk and grep -E 1. c+ matches one or more occurrences of character c 2. c? matches zero or more occurrences of character c 3. expression1 | expression2 matches expression1 or expression 4. ( expr1 | expr2 ) expr3 matches expr1 expr3 , or expr2 expr IV. UNIX Utilities. A. grep -ilnvx pattern { fileName}* = Displays all lines in the file list that contain the pattern. pp. 219- 1. if no filename then standard i/o
2. -i = ignore case. 3. -l = just list of files displayed. 4. -n = line numbers. 5. -v = display all lines that don't match the pattern. 6. -x = line must be an exact match. 7. Examples % cat file1.cpp #include <stdio.h> % grep "std" file1.cpp #include <stdio.h> % grep "Std" file1.cpp % grep -i "Std" file1.cpp #include <stdio.h> % grep -x "std" file1.cpp % grep -x "#include <stdio.h>" file1.cpp #include <stdio.h> % grep -x "#include <Stdio.h>" file1.cpp % grep -xi "#include <Stdio.h>" file1.cpp #include <stdio.h> % grep -xin "#include <Stdio.h>" file1.cpp 1:#include <stdio.h> % grep -lxin "#include <Stdio.h>" file1.cpp file1.cpp B. find pathList expression = Recursively descends through pathList and applies expression to every file. pp.237- 1. -name pattern = True if the file's name matches pattern , which may include shell metacharacters , [].? 2. -print = prints out the name of the current file and returns true if previous criteria have been met. 3. -type ch = True if the type of the file is ch (f = ordinary file, d= directory) 4. -exec command = True if the exit code from executing command is 0. Command must be terminated by an escaped semicolon (;). If you specify {} as a command line argument it is replaced by the name of the current file. 5. -perm octal 6. -size [+-]size_int[c] if c then size in characters, else in 512 byte blocks. + = greater than - = less than specified size 7. -o Short circuiting or. Use ( and ) to surround the clause. 8. [-a] = Short circuiting and. Default, so not needed. 9. find. (-name '.c' -o -name '*.txt' ) –print 10. Examples % find. . ./hw ./hw2/file2.cpp ./hw2/file1.cpp ./file1.cpp % % find. -print . ./hw ./hw2/file2.cpp ./hw2/file1.cpp ./file1.cpp
C. tar -cxtzZvf [tarFileName] fileList pp.233-
1. -c = create 2. -f = filename 3. -t = generates a table of contents. 4. -v = verbose mode 5. -x = extract mode 6. -z = Compress (with -c) or decompress (with –x) using gzip. 7. -Z = Compress (with –c) or decompress (with –x) using compress. 8. tar –czf Old40Files.tar.gz 40/f02 40/s02 would create an archive file named Old40Files.tar.gz that would contain all of the files in 40/f and 40/s02 directories. After being created the file would have been compressed by gzip. V. Shells = a program that is an interface between a user and the raw operating system. A. Built-in commands vs.executable files. cd and umask are built-in commands. Use which utility to determine directory that contains the utility. B. Types and Selecting 1. Bourne ($), Korn ($), C(%), tcsh(%) shells. echo $SHELL /pkg/bin/tcsh 2. chsh doesn’t work in CSIF; Ctrl-D doesn’t work with tcsh. 3. Start with sh, ksh, csh, tcsh C. Shell Variables 1. Hold values in string format 2. Local variables only exist in the shell in which they are defined. 3. Environment variables are passed on to subshells. a. To see them use printenv % printenv LESSOPEN=|/usr/bin/lesspipe.sh %s HISTSIZE= HOSTNAME=pc7.cs.ucdavis.edu LOGNAME=davis HISTFILESIZE= MAIL=/var/mail/davis TERM=xterm HOSTTYPE=i386-linux PATH=/home/davis/bin:.:/sbin:/usr/sbin:/bin:/usr/bin:/usr/ X11R6/bin:/usr/local/bin:/pkg/bin:/usr/local/jdk1.2.2/bin:/ altpkg/java/bin KDEDIR=/usr HOME=/home/davis SHELL=/pkg/bin/tcsh USER=davis QTDIR=/usr/lib/qt-2.1. DISPLAY=: LANG=en_US OSTYPE=linux SHLVL= LS_COLORS=no=00:fi=00:di=01;34:ln=01;36:pi=40;33:so=01;35:bd =40;33;01:cd=40;33;01:or=01;0m=01;35:.png=01;35:.tif=01; : COLORTERM= VENDOR=intel MACHTYPE=i
PWD=/home/davis/40/temp GROUP=users HOST=pc7.cs.ucdavis.edu b. PATH is the list of directories that are searched for executables. c. Uppercase are copies of lowercase. Lowercase are passed to subshells. d. Uppercase Vs Lowercase Examples % echo $user $USER $group $GROUP davis davis users users % set user = fred % echo $user $USER $group $GROUP fred fred users users % set USER = derf % echo $user $USER $group $GROUP fred derf users users % setenv GROUP smith % echo $user $USER $group $GROUP fred derf smith smith % set GROUP = jones % echo $user $USER $group $GROUP fred derf smith jones % tcsh % echo $user $USER $group $GROUP fred fred smith smith % set user = sean % setenv GROUP ECS % echo $user $USER $group $GROUP sean sean ECS ECS % ps PID TTY TIME CMD 9327 pts/0 00:00:00 tcsh 9361 pts/0 00:00:00 tcsh 9382 pts/0 00:00:00 ps % exit exit % ps PID TTY TIME CMD 9327 pts/0 00:00:00 tcsh 9383 pts/0 00:00:00 ps % echo $user $USER $group $GROUP fred derf smith jones % D. Use of \ to extend a line. Don’t follow with a space. % echo this is just a very
? long line this is just a very long line % echo test again
? this test again this % echo test again
? another test again another E. Filename substitution
1. Wild cards are *, ?, [ ]
% find. -name ecs40 -print > findstdout find: ./ecs50: Permission denied % cat findstdout ./News/ecs ./public_html/ecs ./ecs d. Redirected standard out with errors. again % find. -name ecs40 -print > findstdout findstdout: File exists. e. Redirected standard out with errors again with overwrite: % find. -name ecs40 -print >! findstdout find: ./ecs50: Permission denied f. Redirected standard out and standard error with errors % find. -name ecs40 -print >&! findstdout % cat findstdout ./News/ecs ./public_html/ecs find: ./ecs50: Permission denied ./ecs g. Redirected standard out with errors using append. % find. -name ecs40 -print >> findstdout find: ./ecs50: Permission denied % cat findstdout ./News/ecs ./public_html/ecs find: ./ecs50: Permission denied ./ecs ./News/ecs ./public_html/ecs ./ecs h. Redirected standard out and standard error to two different files % rm find* % (find. -name ecs40 -print > findstdout) >& findstderr % cat findstdout ./News/ecs ./public_html/ecs ./ecs % cat findstderr find: ./ecs50: Permission denied H. Piping redirects stdout of process to stdin of next process.
1. Example of piping: % cat grades.txt ID Final Total Pct Grade Maximum 320 979 100 578945 231 852 87 B 514100 281 848 87 B 958134 285 942 96 A 71570 0 131 13 F extra line to show sorting % cat grades.txt | sort
ID Final Total Pct Grade Maximum 320 979 100 extra line to show sorting % cat grades.txt | sort | wc 7 34 152
2. Example of piping and quoting: % find. -name e* -print find: paths must precede expression % find. -name "e" -print ./News/ecs ./public_html/ecs ./public_html/ecs ./public_html/ecs50/echo.csp ./.dt/errorlog.older ./ecs ./ecs50/cusp/explode.exe ./ecs ./ecs ./CUSP/explode.exe ./ecs40.tar ./ecs % find. -name "e" -print | sort ./.dt/errorlog.older ./CUSP/explode.exe ./News/ecs ./ecs ./ecs ./ecs ./ecs40.tar ./ecs ./ecs50/cusp/explode.exe ./public_html/ecs ./public_html/ecs ./public_html/ecs50/echo.csp %
[davis@lect15 notes]$
C. Computation and String Handling:
1. Assignment is simple, e.g., x =5; y = 10 2. Use (( )) construct for numeric computation, e.g. ((z = x + y)) 3. Use ${ variable operator pattern } construct for string manipulation. 4. Given bash-3.00$ filename=/home/davis/archive/hope.tar.gz a. operators # = delete shortest segment that matches pattern at beginning of variable. bash-3.00$ echo ${filename#ho} me/davis/archive/hope.tar.gz b. operator ## = delete longest segment that matches pattern at beginning of variable. bash-3.00$ echo ${filename##ho} pe.tar.gz c. operator % = delete shortest segment that matches pattern at end of variable. bash-3.00$ echo ${filename%ho} /home/davis/archive/ d. operator %% = delete longest segment that matches pattern at end of variable. bash-3.00$ echo ${filename%%ho} / D. Boolean Expressions: 1. test expr1 operator expr2 , or [ expr1 operator expr2 ], or [[ expr1 operator expr2 ]] a. numerical comparison operators are: -eq, -ne, -gt, -ge, -lt, and –le (less than or equal) b. Binary string comparison operators are: =, !=, and == c. the [[ ]] construct allows wild cards 2. test option expr , or [ option expr ] a. String options: -n (not null), -z (is null), and just the string itself tests if it is assigned and not null. b. File attribute testing options: -f (regular), -r (readable), -w (writable), -x (executable), -d (directory), -s (exists and size > 0), and -e (exists), -z (exists but has a size of zero). 3. Logical Operators: && and || E. Control Structures 1. if expr then # expr evaluates to true list elif expr then list else list fi 2. case expr in pattern1 ) list ;; pattern2 | pattern3) list2 ;; *) defaultList esac
[davis@lect15 notes]$ cat compile.sh #! /bin/bash for arg in $@ ; do rm a.out 2> /dev/null if [! -r $arg ] then echo $arg is not readable else if [[ $arg == *.c ]] then if gcc $arg then a.out else echo $arg did not compile fi # if compiling worked elif [[ $arg == *.cpp ]] then g++ $arg if test -e a.out then a.out fi # if a.out exists else echo $arg is not a C or C++ file fi # if arg is .c fi # if readable done [davis@lect15 notes]$ compile.sh hello.c hello.cpp whoops.c bad.c hello.p Hello, C world! Hello, C++ world! whoops.c is not readable bad.c: In function 'main': bad.c:5: error: syntax error before string constant bad.c did not compile hello.p is not a C or C++ file [davis@lect15 notes]$ X. sed [ sed_command ] [-e script ] [-f scriptfile ] { fileName } * A. Edits an input stream according to a script that contains editing commands. B. Surround scripts on command line with single quotes. C. Commands
1. Address is either line number, or a regular expression / /. $ selects last line. 2. Address range can a single address or a couple of addresses separated by commas. If two addresses then the action is applied to all lines between the addresses, inclusive. 3. If no address, then applied to all lines.
4. Append text after line(s). Must be done using a script file. sed address a* text a. sed –f sed1 testhw with sed1 being /printf/ a
/ old style C */ 5. Replace text with change command. Must be done using a script file. sed addressRange *c* text 6. Delete text: sed addressRange d a. sed ‘2,3 d’ test1.hw b. sed ‘/include/d’ test2.txt c. sed ‘/if/endif/ d’ testhw 7. Insert text before line(s). Must be done using a script file. sed address i* text 8. Append the contents of the file name after the line: sed address r filename a. sed ‘4r test2.txt’ testhw 9. Substitute the first occurrence of the regular express with str: sed addressRange s / expr/str / hp9% ps PID TTY TIME COMMAND 1152 ttyp2 0:00 telnetd 1187 ttyp2 0:00 ps 1153 ttyp2 0:00 tcsh hp9% ps|sed s/ttyp/whoops/ PID TTY TIME COMMAND 1152 whoops2 0:00 telnetd 1188 whoops2 0:00 ps 1153 whoops2 0:00 tcsh 1189 whoops2 0:00 sed hp9% echo $path /home/davis/bin /pkg/bin /bin /usr/bin /usr/sbin /usr/dt/bin /usr/bin/X11. /alt pkg/maxplus2/bin hp9% echo $path | sed s/bin/binary/ /home/davis/binary /pkg/bin /bin /usr/bin /usr/sbin /usr/dt/bin /usr/bin/X11. / altpkg/maxplus2/bin 10. Substitute the every occurrence of the regular express with str: sed addressRange s / expr/str / g hp9% echo $path | sed s/bin/binary/g /home/davis/binary /pkg/binary /binary /usr/binary /usr/sbinary /usr/dt/binary / usr/binary/X11. /altpkg/maxplus2/binary hp9% XI. awk -Fc [ -f awkfileName] program {fileName}, where c is field separator if -F option (Glass p. 243) A. If the program is on the command line then surround it with single quotes. B. Processes its input one line at a time applying user-specified awk pattern commands to each line with the format [condition] [{action}] 1. If no condition then action is performed on all lines. 2. If no action then the line is printed to standard out. C. Built-in variables: NF = number of fields in a line; NR = contains the line number of the current line; $1 is first field, $2 is second field .. $NF is the last field.
c. S sleeping d. T traced or stopped e. Z a defunct ("zombie") process f. W has no resident pages g. < high-priority process h. N low-priority task i. L has pages locked into memory (for real-time and custom IO) D. top provides ongoing total system process information and ps sorted by CPU Time E. ps Example [davis@lect15 ~] [davis@lect15 ~]$ find / -name hello >& /dev/null Suspended [davis@lect15 ~]$ ps PID TTY TIME CMD 17613 pts/0 00:00:00 tcsh 17660 pts/0 00:00:00 find 17696 pts/0 00:00:00 ps F. ps Long Format Examples
1. F = Process flags 100 = used super-user privileges 040 = forked but didn't exec 2. UID = Effective User ID 3. PPID = Parent Process ID 4. PRI = Priority. The smaller the value, the higher the priority. 5. NI = Nice 6. SZ = Size. Sizeof the process’ data and stack in kilobytes. [davis@lect15 ~]$ ps -f UID PID PPID C STIME TTY TIME CMD davis 17613 17612 0 13:12 pts/0 00:00:00 -tcsh davis 17660 17613 0 13:24 pts/0 00:00:00 find / -name hello davis 17697 17613 0 13:40 pts/0 00:00:00 ps –f [davis@lect15 ~]$ ps -l F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD 100 S 696 17613 17612 0 72 0 - 722 10817b pts/0 00:00:00 tcsh 000 T 696 17660 17613 0 69 0 - 428 108e50 pts/0 00:00:00 find 000 R 696 17700 17613 0 74 0 - 635 - pts/0 00:00:00 ps G. ps Showing Every Process [davis@lect15 ~]$ ps –ef // shortened by Sean UID PID PPID C STIME TTY TIME CMD root 1 0 0 2002? 00:00:04 init [5] root 2 1 0 2002? 00:00:00 [keventd] root 3 1 0 2002? 00:00:00 [kapm-idled] root 4 1 0 2002? 00:00:02 [kswapd] root 393 1 0 2002? 00:00:00 syslogd -m 0 root 398 1 0 2002? 00:00:00 klogd - rpc 412 1 0 2002? 00:00:03 portmap rpcuser 427 1 0 2002? 00:00:00 rpc.statd root 660 1 0 2002? 00:00:07 /usr/sbin/sshd lp 702 1 0 2002? 00:00:00 lpd Waiting nobody 717 1 0 2002? 00:00:00 rpc.rusersd nobody 729 1 0 2002? 00:00:00 rpc.rwalld xfs 804 1 0 2002? 00:00:17 xfs -droppriv -daemon root 829 1 0 2002 tty1 00:00:00 /sbin/mingetty tty root 830 1 0 2002 tty2 00:00:00 /sbin/mingetty tty
root 835 1 0 2002? 00:00:00 /usr/bin/kdm -nodaemon root 17612 660 0 13:12? 00:00:00 /usr/sbin/sshd davis 17613 17612 0 13:12 pts/0 00:00:00 -tcsh davis 17660 17613 0 13:24 pts/0 00:00:00 find / -name hello davis 17698 17613 0 13:40 pts/0 00:00:00 ps –ef H. ps –u Example [davis@lect15 ~]$ ps -u nobody PID TTY TIME CMD 717? 00:00:00 rpc.rusersd 729? 00:00:00 rpc.rwalld I. top Example [davis@lect15 ~]$ top // shortened by Sean 1:50pm up 10 days, 15 min, 4 users, load average: 0.00, 0.00, 0. 57 processes: 55 sleeping, 1 running, 0 zombie, 1 stopped CPU states: 0.1% user, 0.1% system, 0.0% nice, 0.4% idle Mem: 126640K av, 99544K used, 27096K free, 0K shrd, 5356K buff Swap: 530104K av, 40K used, 530064K free 62936K cached PID USER PRI NI SIZE RSS SHARE STAT %CPU %MEM TIME COMMAND 17704 davis 16 0 968 968 772 R 2.8 0.7 0:00 top 1 root 8 0 544 544 476 S 0.0 0.4 0:04 init 2 root 9 0 0 0 0 SW 0.0 0.0 0:00 keventd 3 root 9 0 0 0 0 SW 0.0 0.0 0:00 kapm-idled 4 root 9 0 0 0 0 SW 0.0 0.0 0:02 kswapd 5 root 9 0 0 0 0 SW 0.0 0.0 0:00 kreclaimd 6 root 9 0 0 0 0 SW 0.0 0.0 0:00 bdflush 7 root 9 0 0 0 0 SW 0.0 0.0 0:00 kupdated 8 root -1 -20 0 0 0 SW< 0.0 0.0 0:00 mdrecoveryd 393 root 9 0 588 588 484 S 0.0 0.4 0:00 syslogd 398 root 9 0 1080 1080 456 S 0.0 0.8 0:00 klogd XIII. Signals A. Programs must deal with events that must interrupt the regular flow of a program. Macro # Default Description SIGINT 2 quit interrupt (Ctrl-C) SIGTRAP 5 dump trace trap (used by debuggers) SIGFPE 8 dump arithmetic exception SIGKILL 9 quit kill (cannot be caught, blocked or ignored.) SIGALRM 14 quit alarm clock SIGTERM 15 quit termination (default for kill utility) SIGUSR1 16 quit user signal 1 SIGCHLD 18 ignore child status changed. SIGSTP 24 suspend suspend. (Ctrl–Z) SIGCONT 25 ignore resume. (fg) B. trap ‘ command_list’ signal_list has the BASH script execute the command_list when one of the signals is caught.
1. An empty command_list has the script ignore the signal listed in the signal_list. 2. Signals can be listed by number, e.g. 1 2 15, or name, e.g., HUP INT TERM XIV. Process control A. Ctrl-Z to suspend the process in the foreground. B. bg to place suspended process in background. C. & at end of command to place process immediately in background.
XV. diff fileName1 fileName A. Compares two files and displays a list of editing changes that would convert the first file into the second file. B. Three kinds of changes listed by diff: additions, deletions, and changes.
1. Additions firstStart a secondStart, secondStop > lines from the second file to add to the first file. 2. Deletions firstStart, firstStop d lineCount < lines from the first file to delete. 3. Changes firstStart, firstStop c secondStart, secondStop < lines in the first file to be replaced ---- > lines in the second file to be used for the replacement ----