Home
4up - The Computer Laboratory
Contents
1. at least not at beginning Why gt LD_LIBRARY_PATH Colon separated list of directories where the loader looks for shared libraries see man 1d so gt LANG LC_ Your locale the name of a system wide configuration file with information about your character set and language country conventions e g en_GB UTF 8 LC_ sets locale only for one category e g LC_CTYPE for character set and LC_COLLATE for sorting order LANG sets default for everything Locale a lists all available locales gt TZ Specification of your timezone mainly for remote users gt OLDPWD Previous working directory also available as 32 Standard environment variables cont d v PS1 The normal command prompt e g PS1 033 7m u h W I 033Em PRINTER The default printer for lpr 1pq and lprm v v TERM The terminal type usually xterm or vt100 v PAGER EDITOR The default pager editor usually Less and emacs respectively v DISPLAY The X server that X clients shall use man 7 environ 33 Plain text files gt File is a sequence of lines trad each lt 80 characters long gt Characters ASCII encoded or extension ISO 8859 1 Latin 1 Microsoft s CP1252 EUC Unicode UTF 8 etc gt Each line ends with a special line feed control character LF Ctrl J byte value 1010 0A16 gt Horizontal tabulator
2. g In a Boolean context the values 0 0 or undef are interpreted as false everything else as true Boolean operators return O or 1 References are typed pointers with reference counting 105 perl arrays Arrays start at index 0 Index of last element of foo is foo length minus 1 Array variables evaluate in a scalar context to array length i e scalar foo foo 1 List values are constructed by joining scalar values with comma operator parenthesis often needed due to precedence rules foo 3 1 h last Lists in lists lose their list identity 1 2 3 equals 1 2 3 Use to generate reference to list e g for nested lists Null list List assignments a undef b c 1 2 3 4 5 equals a 1 b 3 Oc 4 5 Command line arguments are available in ARGV 107 perl scalar literals Numeric constants follow the C format 123 decimal 0173 octal 0x7b hex 3 14e9 float Underscores can be added for legibility 4_294_967_295 String constants enclosed with will substitute variable references and other meta characters In only and WV are substituted header From name i host n Subject subject msgid n print Metacharacters include Strings can contain line feeds multiple source code lines Multiline strings can also be entered with here docs header lt lt EOT From
3. sleep 10 play sounds greeting wav amp unalias dir else dir 1s la xmessage Good Morning Dave amp Outside the body of a function definition the variables 1 2 fi 3 can be used to access the command line arguments passed to a arch ix86 clear echo I m a PC shell script 39 40 Shell history The shell records commands entered These can be accessed in various ways to save keystrokes gt gt gt gt history outputs all recently entered commands I n is substituted by the n th history entry 1I and 1 are equivalent to the previous command 1x is the previous command line minus the first word Use cursor up down keys to access history list modify a previous command and reissue it by pressing Return Type Ctrl O instead of Return to issue command from history and edit its successor which allows convenient repetition of entire command sequences Type Ctrl R to search string in history Most others probably only useful for teletype writers without cursor 41 Startup files for terminal access When you log in via a terminal line or telnet rlogin ssh gt After verifying your password the login command checks etc passwd to find out what shell to start for you As a login shell bash will execute the scripts etc profile profile The second one is where you can define your own environment Use it to
4. activates the Perl debugger see man perldebug gt Option p places the loop while lt gt print around the script such that perl reads and prints every line This way Perl can be used much like sed sed e s sed perl g perl pe s sed perl g gt Option n is like p without the print gt Option ilbackup suffix adds in place file modification to p It renames the input file opens an output file with the original name and directs the input into it For more information man perlrun 119 perl file input output gt open filehandle expr open F1 test dat open file test dat for reading open F2 gt test dat create file test dat for writing open F3 gt gt test dat append to file test dat open F4 datel invoke date and connect to its stdout open F5 mail s test invoke mail and connect to its stdin gt print filehandle list gt close eof getc seek read format write truncate gt lt filehandle gt reads another line from file handle FILE and returns the string Used without assignment in a while loop the line read will be assigned to _ gt lt gt opens one file after another listed on the command line or stdin if none given and reads out one line each time 118 perl a stream editing example Spammers send out unsolicited bulk email junk email for marketing or fraud They harvest millions
5. aon gt matches any character except new line gn gt x matches the preceding item zero or more times gt matches the preceding item one or more times gt matches the preceding item optionally 0 1 times matches start of line gt matches end of line u matches one of listed characters use in character list to negate and for ranges gt C grouping fn m match n m times gt escape following meta character 47 sed a stream editor Designed to modify files in one pass and particularly suited for doing automated on the fly edits of text in pipes sed scripts can be provided on the command line sed e command files or in a separate file sed f scriptfile files General form of a sed command address address command arguments Addresses can be line numbers or regular expressions Last line is One address selects a line two addresses a line range specifying start and end line All commands are applied in sequence to each line After this the line is printed unless option n is used in which case only the p command will print a line The negates address match can group commands per address 46 sed some examples Substitute all occurrences of Windows with Linux command s substitute option g global all occurrences in line sed s Windo
6. include debugging information symbols line numbers 93 95 Version control etiquette v Use diff before commit carefully review what you actually changed This often uncovers editing accidents and left over temporary changes never intended to go into the repository Provide a useful commit message a complete meaningful honest and accurate summary of everything you changed Don t write just bug fixed which or API changed how and why Under git there is a format convention for commit messages a one line summary followed by an empty line followed by details Include function names bug numbers Commit unrelated changes separately Others may later want to undo or merge them separately Commit related changes together Do not forget associated changes to documentation test cases build scripts etc Leave the repository in a usable and consistent state It should always compile without errors and pass tests Avoid dependent or binary files in the repository Diffs on binary files are usually incomprehensible Compiled output should be easy to recreate It just wastes repository space and others can never be sure what is in it 94 gdb the C debugger Best use on binaries compiled with g gt gt un gdb binary run command inside debugger r after setting breakpoints gdb binary core post mortem analysis on memory image of terminated process Enter in s
7. If the kernel does not recognize a command file format the shell will interpret each line of it therefore the is optional for shell scripts Use chmod x file and file or bash file 34 Shell compound commands A list is a sequence of one or more pipelines separated by 3 amp amp amp or and optionally terminated by one of amp or end of line The return value of a list is that of the last command executed in it v list executes list in a subshell e g to contain state changes v list groups a list to override operator priorities gt for variable in words do list done Expands words like command line arguments assigns one at a time to the variable and executes ist for each Example for f in txt do cp f f bak done gt if list then list elif list then list else list fi gt while list do list done until list do list done Any of the above semicolons can instead also be a line feed no required there before the line feed to continue the command on the next line 36 Shell compound commands cont d Boolean tests gt case word in ae a pattern pattern The first ist in the if while and until commands is interpreted as a list Boolean condition The true and false commands return 0 and 1 a respectively note the inverse logic compared to Boolean value
8. S for non whitespace characters Perl provides most standard C and POSIX functions and system calls for Example arithmetic and low level access to files network sockets and other interprocess line mgk25 x 1597 1597 Markus Kuhn homes mgk25 usr bin bash 3 faciliti if line 7 wt 7 d d 7 7 7 communication facilities logname 1 name 2 print logname name n All built in functions are listed in man perlfunc A comprehensive set of add on library modules is listed in man perlmodlib and thousands more are on http www cpan org else die Syntax error in line n For more information man perlre 115 116 perl predefined variables _ The default variable for many operations e g print print _ tr a z A Z _ tr a z A Z while lt FILE gt while _ lt FILE gt Line number of the line most recently read from any file Child process return value from the most recently closed pipe or E operator Error message for the most recent system call equivalent to C s strerror errno Example open FILE test dat die Can t read test dat n For many more man perlvar 117 perl invocation gt First line of a Perl script usr bin perl1 as with shell gt Option e reads code from command line as with sed gt Option w prints warnings about dubious looking code gt Option d
9. Unix_Tools Markus Kuhn Computer Laboratory University of Cambridge http www cl cam ac uk teaching 1516 UnixTools Michaelmas 2015 Part IB Brief review of Unix history v v First Edition developed at AT amp T Bell Labs during 1968 71 by Ken Thompson and Dennis Ritchie for a PDP 11 Rewritten in C in 1973 Sixth Edition 1975 first widely available version Seventh Edition in 1979 UNIX 32V for VAX During 1980s independent continued development at AT amp T System V Unix and Berkeley University BSD Unix Commercial variants Solaris SCO HP UX AIX IRIX IEEE and ISO standardisation of a Portable Operating System Interface based on Unix POSIX in 1989 later also Single Unix Specification by X Open both merged in 2001 The POSIX standard is freely available online http www unix org and http pubs opengroup org onlinepubs 9699919799 Why do we teach Unix Tools gt Second most popular OS family after Microsoft Windows Many elements of Unix have became part of common computer science folklore terminology amp tradition over the past 25 years and influenced many other systems including DOS Windows Many Unix tools have been ported and become popular on other platforms full Unix environment in Apple s OS X Cygwin Your future project supervisors and employers are likely to expect you to be fluent under Unix as a development environment Good examples for high fu
10. humans Markus Kuhn lt Markus Kuhn cl cam ac uk gt 2014 11 25 09 56 20 nice gt very nice Markus Kuhn lt Markus Kuhn cl cam ac uk gt 2014 11 25 09 56 21 copyright notice added Markus Kuhn lt Markus Kuhn cl cam ac uk gt 2014 11 25 09 56 20 second line added Markus Kuhn lt Markus Kuhn cl cam ac uk gt 2014 11 25 09 56 20 adding my first file Markus Kuhn lt Markus Kuhn cl cam ac uk gt 2014 11 25 09 56 20 z SHA1ID Maa E B Row 2 7 Find next prev commit containing i Exact All fields x Search Patch Tree C Diff Old version New version Lines of context 2 3 Ignore space change Line diff Comments Author Markus Kuhn lt Markus Kuhn cl cam ac uk gt 2014 11 25 09 56 20 a filet Committer Markus Kuhn lt Markus Fuhn cl cam ac uk gt 2014 11 25 09 56 20 Parent 24 279544b21491a9400ffab76851a3a24900C49 world gt humans Parent cb8253809e261fae6e5d62bb5dd68cal9 527 82 copyright notice added Child 0elbdb6c27302ba0c8ff1a921c515 lt d4 276552a day gt day Branch master Follows release 1 0 Precedes Merge branch updates 1 0 filel index ba615d9 bf17040 e0b97b2 eee 1 2 1 3 1 3 eee hello world hello humans have a nice day c 2014 M Kuhn xj E J 86 git more useful commands gt git rm filename delete files from both working directory and index gt git add p filename stage only some of the changes you
11. n for i 0 environ i NULL i PENA eas patatengiseali1 Convention main 0 signals return 0 success other values signal errors to calling process 14 Basic shell syntax pipes Start a program and connect the three default file descriptors stdin stdout and stderr to the terminal command Connect stdout of command to stdin of command2 and stdout of command2 to stdin of command3 by forming a pipe commandi command2 command3 Also connects terminal to stdin of commandi to stdout of command3 and to stderr of all three Note how this function concatenation notation makes the addition of command arguments somewhat clearer compared to the mathematical notation command3 command2 commandi arg1 arg2 arg3 ls la sort n k5 less 16 Basic shell syntax sequences Execute several commands or entire pipes in sequence commandi command2 command3 For example date host ryath ds cam ac uk Thu Oct 31 11 48 22 GMT 2013 ryath ds cam ac uk has address 131 111 8 223 Conditional execution depending on success of previous command as in logic expression short cut make ftest amp amp ftest ftest echo Test failed Return value 0 for success is interpreted as Boolean value true other return values for problems or failure as false The trivial tools true and false simply return O and 1 respectively 17 File redirecting advanced
12. 2 else die Syntax error n _ F foreach s sort surname a cmp surname b keys email print email s n F Warning This simple minded solution makes numerous assumptions about how the web page is formatted which may or may not be valid Can you name examples of what could go wrong 122 Conclusions gt Unix is a powerful and highly productive platform for experienced users gt This short course could only give you a quick overview to get you started with exploring advanced Unix facilities gt Please try out all the tools mentioned here and consult the man and info online documentation gt You ll find on http www cl cam ac uk teaching current UnixTools easy to print versions of the bash make and perl documentation links to further resources and hints for installing Linux on your PC Good luck and lots of fun with your projects x x 124
13. accent or with older fonts back quote echo 0BJFILE skipjack o echo which emacs usr bin emacs 24 Pathname expansion Command line arguments containing or are interpreted as regular expression patterns and will be substituted with a list of all matching filenames gt stands for an arbitrary single character gt stands for an arbitrary sequence of zero or more characters gt stands for one character out of a specified set Use to specify range of characters and to complement set Certain character classes can be named within None of the above will match a dot at the start of a filename which is the naming convention for hidden files Examples bak A Za z 7 alpha A Z files o0 Job control Start command or entire pipe as a background job without connecting stdin to terminal command amp 1 4739 testrun 2 gt amp 1 gzip 9c gt results gz amp 2 4741 testruni amp testrun2 amp testrun3 amp 3 5106 4 5107 5 5108 Shell prints both a job number identifying all processes in pipe as well as process ID of last process in pipe Shell will list all its jobs with the jobs command where a sign marks the last stopped default job 25 27 Quote removal Three quotation mechanisms are available to enter the special characters in command line arguments without triggering the correspo
14. directory with a symbolic link named RCS to the shared directory As long as nobody touches the v files or manually changes the write permissions on working files only one team member at a time can edit a file and old versions are never lost The rcs command can be used by a team leader to bypass this policy and break locks or delete old revisions RCS remains useful for quickly maintaining history of single files as an alternative to manually making backup copies of such files RCS is no longer commonly used for joint software development If you work in a distributed team on a project with subdirectories need remote access want to rename files easily or simply hate locks use svn or git instead 58 svn repository and working directories svnadmin create Subversion repository URL file homes mgk25 SVN svi update D commit svn commit svn update Working directory eve saarel fos as Working directory of user 1 of user 3 svn checkout Working directory svn checkout of user 2 svn checkout Team administrator first creates repository svnadmin create Team members create personal working directories svn checkout Team members repeatedly fetch latest version svn update and return their changes svn commit 60 svn Subversion vs CVS Subversion was specifically written to replace an older system CVS which in turn started out as a layer on top of RCS for managing entire directory
15. fapp2 rjal4 cam ac uk mgk25 cam ac uk fapp2 cam ac uk rjai4 cam ac uk rm slides bak aux dvi log ps This bash extension is not required by the POSIX standard e g Ubuntu Linux bin sh lacks it Tilde expansion Provides convenient entry of home directory pathname echo pb Mail inbox nhome pb homes mgk25 Mail inbox The builtin echo command simply outputs argv to stdout and is useful for demonstrating command line expansion and for single line text output in scripts 23 Shell command line preprocessing A number of punctuation characters in a command line are part of the shell control syntax amp lt gt or can trigger special convenience substitutions before argv is handed over to the called program gt brace expansion v tilde expansion gt parameter expansion gt pathname expansion filename matching gt quote removal 22 Parameter and command expansion Substituted with the values of shell variables OBJFILE skipjack o echo OBJFILE OBJFILE o c skipjack o skipjack c echo HOME PATH LOGNAME nomes mgk25 bin usr bin usr local bin usr X11R6 bin mgk25 or the standard output lines of commands which emacs usr bin emacs echo which emacs usr bin emacs ls 1 which emacs rwWXr xr x 2 root system 3471896 Mar 16 2001 usr bin emacs Shorter alternatives variables without braces and command substitution with grave
16. file changed 1 insertion 1 deletion git checkout master Switched to branch master sed i s day day filet git commit a m day gt day master ad469e5 day gt day 1 file changed 1 insertion 1 deletion git log graph decorate oneline branches ad469e5 HEAD master day gt day 152b0d0 Merge branch updates 1 0 I 610b41a world gt humans cb87e76 updates 1 0 nice gt very nice I c1 332c copyright notice added a324cdc tag release 1 0 second line added 5f 3b6b2 adding my first file 85 git storage areas working dir Where you edit the files of your project index A staging area separate from the working directory also located inside git where git add transfers modified files to prepare the next commit repository Database holding a directed acyclic graph of commits vertices and parent pointers edges along with refs i e tags branch heads HEAD Located in git subdirectory of the root of the working directory stash A temporary storage area also located inside git into which work in progress items from the working directory can be transfered if the working directory is needed for other work 87 s gitk wd1 day gt day Markus Kuhn lt Markus Kuhn cl cam ac uk gt 2014 11 25 09 56 21 Merge branch updates 1 0 Markus Kuhn lt Markus Kuhn cl cam ac uk gt 2014 11 25 09 56 20 world gt
17. i e not located inside a git subdirectory of a working directory for others to push into gt git pull Fetch updates from another repository default origin and merge them into local working directory gt git fetch Fetch updates from remote branches from another repository default origin but do not yet merge them into the local working directory gt git push Forward local revisions to another repository Works only if the destination repository is bare or has no uncommitted changes in its working directory gt git remote v list tracked other repositories with URLs 92 git more information Tutorial man gittutorial https www kernel org pub software scm git docs gittutorial html Manual https www kernel org pub software scm git docs user manual html Git for computer scientists repository data structure http eagain net articles git for computer scientists Git concepts simplified http gitolite com gcs html cc gcc the C compiler Example cat hello c include lt stdio h gt int main printf Hello World n return 0 gcc o hello hello c hello Hello World Compiler accepts source c and object 0 files Produces either final executable or object file option c Common options gt W Wall activate warning messages better analysis for suspicious code gt 0 activate code optimizer gt g
18. made to filename in the index if you do not want all your changes to go into the same commit gt git diff compare working directory and index gt git diff staged compare index and HEAD gt git diff HEAD compare working directory and HEAD gt git stash moves all current usually unfinished differences between HEAD and the working directory and index into a stash memory then reset the working directory and index to HEAD like git reset hard useful to work on something else for a while in the middle of something gt git stash pop retrieve stashed changes back into the working directory 88 git fixing accidents Fixing uncommitted mistakes in the working directory or index gt git reset filename restore filename in the index from HEAD useful to undo git add lrm filename gt git checkout filename restore filename in the working directory from HEAD to undo uncommitted changes Fixing very recently committed mistakes aka rewriting history gt git reset soft HEAD reset the current branch head to its parent e g to immediately undo the last git commit gt git commit amend replace the most recent commit to fix a mistake in the commit message gt git rebase commit rewite the commit history of the current branch to use commit as the new starting point If collaborators might already have fetched your erroneous commit it is usually far better to fix the m
19. o lt data gz demo lt gzip c gt gt file name of the target of the rule gt lt name of the first prerequisite gt names of all prerequisites Environment variables automatically become make variables for example HOME A in a shell command has to be entered as 101 perl the Swiss Army Unix Tool v a portable interpreted language with comprehensive library gt combines some of the features of C sed awk and the shell gt the expression and compound statement syntax follows closely C as do many standard library functions gt powerful regular expression and binary data conversion facilities make it well suited for parsing and converting file formats extracting data and formatting human readable output gt offers arbitrary size strings arrays and hash tables gt garbage collecting memory management gt dense and compact syntax leads to many potential pitfalls and has given Perl the reputation of a write only hacker language gt widely believed to be less suited for beginners numerical computation and large scale software engineering but highly popular for small to medium sized scripts and Web CGI 103 make implicit rules phony targets Implicit rules apply to all files that match a pattern h eps 4 gif giftopnm lt pnmtops noturn gt eps h jpg djpeg lt pnmtops noturn gt make knows a number of implicit rules
20. start with a TAB character ASCII 9 97 99 make a project build tool The files generated in a project fall into two categories gt Source files Files that cannot be regenerated easily such as e working files directly created and edited by humans files provided by outsiders results of experiments gt Derived files Files that can be recreated easily by merely executing a few shell commands such as object and executable code output from a compiler output of document formatting tools output of file format conversion tools results of post processing steps for experimental data source code generated by other programs files downloaded from Internet archives 98 make writing a Makefile cont d Examples demo demo c demo h gcc g 0 o demo demo c data gz demo demo gzip c gt data gz Call make with a list of target files as command line arguments It will check for every requested target whether it is still up to date and will regenerate it if not gt It first checks recursively whether all prerequisites of a target are up to date gt It then checks whether the target file exists and is newer than all its prerequisites gt If not it executes the regeneration commands specified Without arguments make checks the targets of the first rule 100 make variables Variables can be used to abbreviate rules CC gcc CFLAGS g 0 demo demo c demo h CC CFLAGS
21. you delete a version controlled file with rm the next svn update will restore it 61 63 svn setting up Create new repository e g SVN separate from working directory svnadmin create SVN Then checkout a working copy of the repository into a new working directory wdir referring to the repository via its URL svn checkout file HOME SVN wdir Note that every subdirectory in your new working directory has a svn subdirectory This contains among other things the URL of your repository see svn info Therefore inside the working directory it is no longer necessary to add that repository URL as an argument to svn operations Now populate the repository with content gt Create or move into the working directory some files gt Register them with Subversion svn add gt Push them into the repository svn commit Then every team member after their own initial svn checkout does gt Pull the latest version svn update gt Make edits gt Push them back to the repository svn commit 62 svn querying the working directory status gt svn status List all files that differ between your working directory and the repository The status code shown indicates e A added this file will appear in the repository e D deleted this file will disappear from the repository e M modified you have edited this file e R replaced you used svn delete followed by svn add e C conflict at the last upd
22. your files to the staging area Specifying a directory will recursively add all files and directories in it e g git add imports everything gt git status List which files are already in the staging area Option s results in a compacter output format gt git commit Create the first snapshot of your project by saving whatever is in the staging area as your first commit in the repository git commit will fire up EDITOR for you to enter a commit message This can also be provided via command line option m commit message 7 git your first commit Setting your name Git records your name and email address with each commit If you have never used git before git commit will invite you to first set those details once in gitconfig using J git config global user name Your Name Comes Here I git config global user email you yourdomain example com gt git log Show the list of commits you have made so far Option p patch shows changes made to each file gt gitk GUI tool for browsing commits gt git tag tagname commit Associate a human readable name tag with a commit git log commit 5f3b6b271a048135615805fd705adf2a89225611 Author Markus Kuhn lt Markus Kuhn cl cam ac uk gt Date Tue Nov 25 10 11 09 2014 0000 adding my first file 79 git getting started fj mkdir wdl J cd wdi git init Initialized empty Git repository in wd1 git ls AF git
23. HT TAB Ctrl l byte value 9 advances the position of the next character to the next multiple of 8 column Some systems e g DOS Windows some Internet protocols end each line instead with a two control character sequence carriage return CR Ctri M 1310 ODi plus line feed Different end of line conventions and different ASCII extensions make conversion of plain text files necessary dos2unix iconv Very annoying Alternative flowed plain text format no LF is stored inside a paragraph line wrapping of paragraph happens only while a file is being displayed LF terminates paragraph Some plain text editors e g Windows Notepad start each UTF 8 plain text file with a Unicode Byte Order Mark BOM U FEFF EFie6 BB16 BF16 which is not normally used under Unix 35 Executable files and scripts Many files signal their format in the first few magic bytes of the file content e g Ox7f E L F signals the System V Executable and Linkable Format which is also used by Linux and Solaris The file tool identifies hundreds of file formats and some parameters based on a database of these magic bytes file which 1s bin 1ls ELF 32 bit LSB executable Intel 80386 The kernel recognizes files starting with the magic bytes as scripts that are intended for processing by the interpreter named in the rest of the line e g a bash script starts with bin bash
24. No single central repository more reliable and democratic gt Each participant holds a local repository of the revision history gt Committing and uploading a commit to another site are separate actions i e commits branches etc can be done off line gt Creating and merging branches are quick and easy operations gt Branches do not have to be made visible to other developers gt Revisions identified by secure hash value rather than integer Distributed version control systems are far more flexible and powerful than centralized ones like Subversion but require more experience 75 svn sharing an svn ssh server securely The ease of setting up your own svn ssh server makes it tempting to share that access with other team members to grant them access to your repository However simply granting others access to your ssh login by adding their public keys to your ssh authorized_keys file would also give them full shell access to your account Fortunately OpenSSH allows you to restrict what access someone else s public key in your ssh authorized_keys file grants In particular the command option allows you to constrain the owner of that key to only execute a single program running under your user identity command svnserve t tunnel user gsm10 r home mgk25 SVN no port forwarding no agent forwarding no X11 forwarding no pty ssh dss AAAB3 ogUc gsmi0 cam ac uk Adding gsm10 s ssh pu
25. Open other file descriptors for input output or both command O lt in 1 gt out 2 gt gt log 3 lt auxin 4 gt auxout 5 lt gt data Here Documents allow us to insert data into shell scripts directly such that the shell will feed it into a command via standard input The lt lt is followed immediately by an end of text marker string tr lt lt THEEND A MN Za mn z N ZA Mn za m gt Vs lbh zhfg cbfg n ehqr wbxr ba HFRARG ebgngr gur gt nycunorg ol 13 punenpgref naq nqq n jneavat gt THEEND Redirecting to or from dev tcp hostname port will open a TCP socket connection echo GET mgk25 iso paper c gt amp 3 cat lt amp 3 3 lt gt dev tcp www cl cam ac uk 80 The above example is a bash implementation of a simple web browser It downloads and displays the file http www cl cam ac uk mgk25 iso paper c Bash s dev tcp feature is disabled in some Linux distributions security concerns 19 File redirecting basics Send stdout to file command gt filename Append stdout to file command gt gt filename Send both stdout and stderr to the same file First redirect stdout to filename then redirect stderr file descriptor 2 to where stdout goes target of file descriptor 1 amp 1 command gt filename 2 gt amp 1 Feed stdin from file command lt filename 18 Command line argument conventions Each program receives from the caller as a parameter an array of strings argv
26. The shell places into the argv parameters the words entered following the command name after several preprocessing steps have been applied first cp Lecture Timetable pdf lecture timetable pdf mv bak old files Command options are by convention single letters prefixed by a hyphen h Unless followed by option parameters single character flag options can often be concatenated ls l a t 1s lat GNU tools offer alternatively long option names prefixed by two hyphens help Arguments not starting with hyphens are typically filenames hostnames URLs etc gcc version curl head http www cl cam ac uk 20 Command line argument conventions cont d 1 The special option signals in many tools that subsequent words are arguments not options This provides one way to access filenames starting with a hyphen rm i rm i The special filename signals often that standard input output should be used instead of a file All these are conventions that most but not all tools implement usually via the getopt library function so check the respective manual first uon The shell remains ignorant of these conventions http pubs opengroup org onlinepubs 9699919799 basedefs V1_chap12 html 21 Brace and tilde expansion Brace expansion Provides for convenient entry of words with repeated substrings echo af b c d te abe ace ade echo mgk25
27. a pub and 7 ssh id_dsa Protect id_dsa like a password Remote machine will not ask for password with ssh if your private key ssh id_dsa fits one of the public keys locks listed on the remote machine in ssh authorized_keys On MCS Linux your Novell server home directory with ssh authorized_keys is mounted only after login and therefore no password free login for first session 52 rsync rsync options source destination An improved cp gt The source and or destination file directory names can be prefixed with user hostname if they are on a remote host gt Uses ssh as a secure transport channel may require e ssh gt Options to copy recursively entire subtrees r preserve symbolic links 1 permission bits p and timestamps t gt Will not transfer files or parts of files that are already present at the destination An efficient algorithm determines which bytes actually need to be transmitted only very useful to keep huge file trees synchronised over slow links Application example Very careful backup rsync e ssh v rlpt delete backup backup dir OLD date Im me myhost org mycopy Removes files at the destination that are no longer at the source but keeps a timestamped copy of each changed or removed file in mycopy OLD yyyy mm dd so nothing gets ever lost 53 gzip amp friends compressing byte streams
28. ails follow svn E160028 File file1 is out of date svn update Updating C file1 A file2 Updated to revision 2 Conflict discovered in file1 Select p postpone df show diff e edit file m merge mc my side of conflict tc their side of conflict s show all options p Summary of conflicts Text conflicts 1 70 svn a working example User 1 svn update Updating U file1 Updated to revision 3 cat filet hello humans and dogs svn diff c3 Index filei file1 revision 2 filet revision 3 1 1 hello humans t hello humans and dogs 72 svn remote access The URL to an svn repository can point to a gt local file file gt Subversion WebDAV Apache server http or https gt Subversion server svn gt Subversion accessed via ssh tunnel svntssh Setting up an svn or http server may be complicated in some environments administrator account required firewall rules etc An svntssh server is much easier to set up and only needs gt an existing SSH server gt your public key in ssh authorized_keys gt usr bin svnserve A command like svn list svntssh mgk25 linux home mgk25 SVN will run ssh mgk25 linux svnserve t to start the remote server and will then talk to it using the Subversion protocol over stdin stdout 73 Distributed revision control systems Popular examples git mercurial bazaar gt
29. ample gt References to anonymous hash tables can be created with pee z Se ae reece E aco nr i logname pw uid gid name home shell user For more information man perlref line join J join gt reverse Cuser 113 114 perl more standard functions perl regular expressions gt Perl s regular expression syntax is similar to sed s but are metacharacters and need no backslashes chop chomp lc uc lcfirst ucfirst Remove trailing character linefeed Change entire string or first character gt Substrings matched by regular expression inside are assigned from string to lowercase uppercase l pack unpack di ord to variables 1 2 3 and can be used in the replacement build parse binary records ASCII 4 integer conversion string of as expression sprintf hex oct z format strings and numbers oe b gt The substring matched by the regex pattern is assigned to amp the shift unshift push pop aa a unmatched prefix and suffix go into and add remove first last array element aea eines er bea f die warn z i scalar list gontet ea gt Predefined character classes include whitespace s digits d abort program with error warning ga lbh h ter Th ti i i map grep require use aipnanumer c or _ Character w e respective complemen Iterate over or filter list elements Import library module classes are defined by the corresponding uppercase letters e g
30. at a name identifies a subroutine This is usually redundant thanks to a prior sub declaration or parenthesis The third case passes _ on as parameters gt Parameters are passed as a flat list of scalars in the array _ gt Perl subroutines are call by reference that is _ 0 are aliases for the actual parameters Assignments to _ elements will raise errors unless the corresponding parameters are lvalues gt Subroutines return the value of the last expression evaluated or the argument of a return statement It will be evaluated in the scalar list context in which the subroutine was called gt Use my a b to declare local variables a and b within a block For more information man perlsub 109 111 perl syntax cont d gt Loop control e last immediately exits a loop e next executes the continue block of a loop then jumps back to the top to test the expression e redo restarts a loop block without executing the continue block or evaluating the expression gt The loop statements while for or foreach can be preceded by a label for reference in next last or redo instructions LINE while lt STDIN gt next LINE if discard comments gt No need to declare global variables For more information man perlsyn 110 perl operators gt Normal C Java operators h lt gt gt amp 7 amp amp II gt Exponentiation gt Numeric
31. ate there was a conflict between your local changes and independent changes in the repository which you still need to resolve manually e unversioned file is not in repository suppress q e missing file in repository but not in working dir gt svn diff filenames Show what you changed so far compared to the base version that you got at your last checkout or update gt svn info Show metadata about the working directory revision of last update URL of repository etc 64 svn commits and updates gt svn commit filenames Check into the repository any modifications additions removals of files that you did since your last checkout or commit Option m provides a commit log message without it svn commit will call EDITOR for you to enter one gt svn update filenames Apply modifications that others committed since you last updated your working directory This will list in the first column a letter for any file that differed between your working directory and the repository Apart from the letter codes used by status it also may indicate e U updated get newer version of this file from repository e G merged conflict but was automatically resolved Remaining conflicts indicated as C must be merged manually To assist in manual merging of conflicts the update operation will write out all three file versions involved all identified with appropriate filename extensions as
32. blic key with the above prefixes to my own ssh authorized_keys file all in one line will only allow him to start up and communicate with an svnserve t command which is further constrained to access only repositories under home mgk25 SVN and to log all his commits under his user identity gsm10 The other options disable various network port forwarding facilities of ssh that are not required here See man sshd and the svn book for details Consult your system administrator before using this technique os git a distributed revision control system gt Created by Linus Torvalds in 2005 to manage Linux kernel gt Now the most popular distributed revision control system gt Used by a large number of open source projects gt Integrated in many free and commercial development environments gt Supported by major web source code hosting sites github etc gt Can interface with Subversion repositories gt Git archives snapshots of a directory tree rather than trying to record edit operations e g renaming files 76 git basic usage your own project gt git init Start using git by executing this once in the root of your project working directory This creates the hidden subdirectory git which now contains your repository your staging area index and a configuration file git config gt git add file Prepare creating the first snapshot commit of your project by copying adding
33. by default for instance WO hve CC c CPPFLAGS CFLAGS lt It is customary to add rules with phony targets for routine tasks that will never produce the target file and just execute the commands clean rm f bak o TARGETS core Common phony targets are clean test install 102 perl data types Perl has three variable types each with its own name space The first character of each variable reference indicates the type accessed a scalar an array of scalars an associative array of scalars hash table selects an array element queries a hash table entry Examples of variable references days the value of the scalar variable days days 28 element 29 of the array days days Feb the Feb value from the hash table days days last index of array days days days 0 days days days 3 4 5 days 3 5 days a c days a days c days keyl vall key2 val2 104 perl scalar values A scalar variable can hold a string number or reference Scalar variables can also hold the special undef value set with undef and tested with defined Strings can consist of bytes or characters Unicode UTF 8 More on Unicode character strings man perluniintro Numeric decimal and string values are automatically converted into each other as needed by operators 5 13
34. comparison lt gt lt gt lt gt gt String comparison eq ne cmp 1t gt le ge v String concatenation a a a eq ax3 v Apply regular expression operation to variable line s sed perl g gt gt executes a shell command v returns list with a number range in a list context and works as a flip flop in a scalar context for sed style line ranges For more information man perlop 112 perl references perl examples of standard functions Scalar variables can carry references to other scalar list hash table or split pattern expr subroutine values Splits string into array of strings separated by pattern gt To create a reference to another variable subroutine or value prefix join expr list it with Much like amp in C Joins the strings in last into a single string separated by value of ee uss expr gt To dereference such a reference prefix it with or amp according to the resulting type Use around the reference to reverse list clarify operator precedence a is short for a Reverse the order of elements in a list Can also be used to invert hash tables gt Hash table and list references used in a lookup can also be dereferenced with gt therefore a gt john is short for substr expr offset len a john and b gt 5 is short for b 5 Extract substring gt References to anonymous arrays can be created with Ex
35. e and modify the software in any way as long as e you respect the identity and rights of the author preserve copyright notice and licence terms in source code and documentation e you agree not sue the author over software quality accept exclusion of liability and warranty gt GNU General Public Licence GPL requires in addition that any derived work distributed or published e must be licensed under the terms of the GPL e must have its source code made publicly available Numerous refinements and variants of these licences have been written For more information on the various opensource licence types and their philosophies http opensource org Photo Bell Labs VT100 terminals Unix tools design philosophy and later video display terminals such as the DEC VT100 all providing 80 characters per line fixed width ASCII output Their communications protocol is still used today in graphical windowing environments via terminal emulators e g xterm konsole gt Compact and concise input syntax making full use of ASCII repertoire to minimise keystrokes gt Output format should be simple and easily usable as input for other programs gt Programs can be joined together in pipes and scripts to solve more complex problems gt Each tool originally performed a simple single function gt Prefer reusing existing tools with minor extension to rewriting a new Photo http www catb org
36. echo hello world gt filel git status s filet untracked file git add filel git status s A fileli changes to be committed git commit m adding my first file master root commit 5f3b6b2 adding my first file 1 file changed 1 insertion create mode 100644 filel Each commit is automatically named using a 20 bytes 40 hex digits pseudo random byte string often abbreviated into a unique prefix 5f3b6b2 HEAD can be used as a synonym for the latest commit 78 git adding more commits tagging echo have a nice day gt gt file1 git add filet git commit m second line added master a324cdc second line added 1 file changed 1 insertion git tag release 1 0 HEAD git log graph decorate oneline a324cdc HEAD tag release 1 0 master second line added 5f 3b6b2 adding my first file sed i s world humans filet git commit a m world gt humans master 610b41a world gt humans 1 file changed 1 insertion 1 deletion git log graph decorate oneline 610b41a HEAD master world gt humans a324cdc tag release 1 0 second line added 5f3b6b2 adding my first file 80 git branching and merging git objects in repository branch heads commit A saved snapshot of a project tree of files and Commits form a directed acyclic graph in the lt directories stored in a repository Includes metadata repository K gt pointer s to parent commit s Each comm
37. esr writings taouu html tool from scratch The VT100 was the first video terminal with microprocessor and the first gt The main user interface software shell is a normal replaceable to implement the ANSI X3 64 ECMA 48 control functions For program without special privileges instance Esc 7m activates and sc Om returns to 7 T gt Support for automating routine tasks normal where Esc is the ASCII escape control character 27 0x1B PP E http www vt100 net Brian W Kernighan Rob Pike The Unix Programming Environment Prentice Hall 1984 http www ecma international org publications standards Ecma 048 htm man console_codes Unix documentation Most Unix documentation can be read from the command line Classic manual sections user commands 1 system calls 2 library functions 3 devices 4 file formats 5 gt The man tool searches for the manual page file MANPATH and activates two further tools nroff text formatter and more text file viewer Add optional section number to disambiguate man 3 printf C subroutine not command Honesty in documentation Unix manual pages traditionally include a BUGS section gt xman X11 GUI variant offers a table of contents gt info alternative GNU hypertext documentation system Invoke with info from the shell of with C h i from emacs Use M enu key to select topic or Enter to select hyperlink under cursor N ext P rev U
38. gt gzip file convert file into a compressed file gz using a Lempel Ziv Huffman algorithm gt gunzip file decompress gz files gt un compress file de compress Z files older tool using less efficient and patented LZW algorithm gt blun zip2 file de compress bz2 files newer tool using Burrows Wheeler blocktransform gt zcat file decompress Z gz to stdout for use in pipes gt Extract compressed tar archive zcat archive tar gz tar xvf tar xvzf archive tgz GNU tar only 55 tar converting file trees into byte streams and back Originally tape archiver Create archive recurses into subdirectories tar cvf archive tar files Show archive content tar tvf archive tar Extract archive tar xvf archive tar files 54 diff patch managing file differences gt diff oldfile newfile Show difference between two text files as lines that have to be inserted deleted to change oldfile into newfile Option u gives better readable unified format with context lines Option r compares entire directory trees diff u example bak example txt diff example bak example txt example bak 2c2 3 example txt lt this sentence no verb 1 2 1 3 sca an unmodified line gt this sentence has a verb this sentence no verb gt a newly added line this sentence has a verb a ne
39. hell ulimit c 100000 before test run to enable core dumps Core dump can be triggered by gt gt a user pressing Ctrl SIGQUIT a fatal processor or memory exception segmentation violation division by zero etc 96 gdb some common commands gt bt print the current stack backtracing function calls gt p expression print variable and expression values gt up down move between stack frames to inspect variables at different function call levels gt b set breakpoint at specified line or function gt r run program with specified command line arguments gt s continue until next source code line skip function calls gt n continue until next source code line follow function calls Also consider starting gdb within emacs with ESC x gdb which causes the program counter position to be indicated in source file windows make writing a Makefile Many derived files have other source or derived files as prerequisites They were generated from these input files and have to be regenerated as soon as one of the prerequisites has changed and make does this A Makefile describes gt which target file in a project is derived gt on which other files that target depends as a prerequisite gt which shell command sequence will regenerate it A Makefile contains rules of the form target1 target2 prereqi prereq2 command1 command2 Command lines must
40. ient and provides the login screen After successful login the xdm starts a shell script Xstartup as root and a shell script Xsession as the user Xsession then starts all the components of the desktop environment This includes in particular a window manager often also a separate session and or desktop manager and several auxiliary servers for inter application communication dbus ssh agent etc The window session or desktop managers finally allow the user to start application processes xterm etc 44 Desktop environment cont d Logout gt Most X clients are started as background processes An exception is the session or window manager which Xsession starts as the last foreground process gt If the session or window manager terminates the Xsession script ends as well This causes the xdm to reset the X server which closes the connection to and thereby terminates all the X clients gt Finally xdm presents the login screen again The detailed behaviour of Xsession and the session manager differs significantly across desktop environments and Unix Linux distributions and usually offer many hooks and options for configuration auto start of applications X servers also manage a database of keyboard mappings and client configuration options see man xmodmap man xrdb man X man xdm 45 sed regular expressions Regular expressions enclosed in Some regular expression meta characters
41. istake with a follow up commit than rewriting history Otherwise all collaborators working from your erroneous commit will have to rebase their branches to your fixed commit Read man git reset carefully 89 git multiple working directories collaboration git init git clone ay git pull git repository lt gt repository URL git or http or ssh git push git pas Pose commit Working directory git wont Pose commit Working directory and index of user 2 and index of user 1 Each working directory contains an associated repository index and stash ina git subdirectory of its top level directory 91 git information flow between storage areas index local stash working directory staging area repository git add rm git commit F reset git rebase rebase E a S S git stash save git stash pop git stash apply git diff staged git aist mean diff HEAD 90 git basic collaboration commands gt git clone url Copy an existing repository and create an associated working directory around it unless bare is used A cloned repository will remember the URL of the origin repository where it came from Supports remote repository access via SSH e g git clone ssh mgk25 linux cl ds cam ac uk home mgk25 wd1 gt git init bare Create a new bare repository without associated a working directory
42. it can be the parent of multiple Gpaates 1 0 gt date and author of theccommit other commits branches and each commit O o can have multiple other commits as parents merge gt description merge Identified through a 160 bit string 40 hex digits the Branches riect diverse lines ot development SHA 1 hash of the file tree and metadata It represents a mi res brine thesetoreth tag version of your software the state of your project s files at ges bring these together again 7 some point in time Tags add human friendly names to some Ga tag Descriptive name e g release 2 4 7 pointing to a commits particular commit Can be associated with commits after Branch heads move along with each commit to _ initial commit their creation Tags are intended to keep pointing at the them tag references remain where they are same commit but can be edited later branch A line of development Another descriptive name with a pointer to a commit branch head but unlike a tag that C ref pointer is updated automatically whenever a new commit arrives on that branch Name of default branch master Commits not reachable from any tag or branch G Sommi head will be garbage collected 81 man gitglossary 82 git branching and merging git branching example gt git branch list branches mark current one HEAD with gt git branch branchname start a new branch off HEAD git branch gt git branch branchname startpoin
43. me not supported by shell supported by shell 13 File descriptors Unix processes access files in three steps gt Provide kernel in open or creat system call a path name and get in return an integer file descriptor gt Provide in read write and seek system calls an opened file descriptor along with data gt Finally call close to release any data structures associated with an opened file position pointer buffers etc The 1lsof tool lists the files currently opened by any process Under Linux file descriptor lists and other kernel data can be accessed via the simulated file system mounted under proc As a convention the shell opens three file descriptors for each process gt 0 standard input for reading the data to be processed gt 1 standard output for the resulting output data gt 2 standard error for error messages 15 Command line arguments return value environment A Unix C program is invoked by calling its main function with gt a list of strings argv as an argument gt a list of strings environ as a predefined global variable include lt stdio h gt Environment strings have the form extern char environ name value int main int argc char argv int i printf Command line arguments n for i 0 i lt argc i where name is free of Argument argv 0 is usually the puts argv i name or path of the program printf Environment
44. name i host Subject subject msgid EOT 106 perl hash tables v Literal of a hash table is a list of key value pairs wage adam 19 bob 22 charlie 7 Using gt instead of comma between key and value increases readability wage adam gt 19 bob gt 22 charlie gt 7 Access to hash table age age john age adam 6 Remove entry delete age charlie Get list of all keys family keys age Use to generate reference to hash table Environment variables are available in ENV For more information man perldata 108 perl syntax gt Comments start with and go to end of line as in shell gt Compound statements if expr block elsif expr block else block while expr block continue block for expr expr expr block foreach var list block Each block must be surrounded by no unbraced single statements as in C The optional continue block is executed just before expr is evaluated again gt The compound statements if unless while and until can be appended to a statement n 0 if n gt 9 do x gt gt 1 until x lt 64 A do block is executed at least once perl subroutines sub max my x y _ A a Subroutine declaration Teen eens ae sub name block 3 y gt Subroutine call m max 5 7 name List print max m n name list amp name A amp prefix clarifies th
45. nctionality user interfaces This short lecture course can only give you a first overview You need to spend at least 2 3 times as many hours with e g MCS Linux to gt gt explore the tools mentioned solve exercises which often involve reading documentation to understand important details skipped in the lecture A brief history of free Unix In 1983 Richard Stallman MIT initiates a free reimplementation of Unix called GNU GNU s Not Unix leading to an editor emacs compiler gcc debugger gdb and numerous other tools In 1991 Linus Torvalds Helsinki CS undergraduate starts development of a free POSIX compatible kernel later nicknamed Linux which was rapidly complemented by existing GNU tools and contributions from volunteers and industry to form a full Unix replacement In 1991 Berkeley University releases a free version of BSD Unix after removing remaining proprietary AT amp T code Volunteer projects emerge to continue its development FreeBSD NetBSD OpenBSD In 2000 Apple releases Darwin the now open source core components of their OS X and iOS operating systems Volunteer projects emerge to port many Unix tools onto Darwin Homebrew Fink MacPorts GNU Darwin etc Free software license concepts Original Unix user interfaces The initial 1 O devices were teletype terminals gt public domain authors waive all copyright gt MIT BSD licences allow you to copy redistribut
46. nding shell substitution gt suppresses all special character meanings gt suppresses all special character meanings except for gt suppresses all special character meanings for the immediately following character Example echo HOME HOME homes mgk25 HOME The bash extension provides access to the full C string quoting syntax For example x1b is the ASCII ESC character 26 Job control cont d Foreground job Stdin connected to terminal shell prompt delayed until process exits keyboard signals delivered to this single job Background job Stdin disconnected read attempt will suspend job next shell prompt appears immediately keyboard signals not delivered shell prints notification when job terminates Keyboard signals keys can be changed with stty tool gt Ctrl C intr SIGINT 2 by default aborts process gt Ctrl quit SIGQUIT 3 aborts process with core dump gt Ctrl Z susp SIGSTOP 19 suspends process Another important signal not available via keyboard gt SIGKILL 9 destroys process immediately 28 Job control cont d Job control commands gt fg resumes suspended job in foreground gt bg resumes suspended job in background gt kill sends signal to job or process Job control commands accept as arguments gt process ID gt job number gt command name Examples ghostview p
47. of valid email addresses for example from web pages To make email addresses in your web pages slightly harder to harvest you can avoid the sign in the HTML source For instance convert lt a href mailto jdoe acm org gt jdoe acm org lt a gt into lt a href mailto jdoe 40acm org gt jdoek 64 acm org lt a gt The lines perl pi bak lt lt EOT html s href mailto 7 1 40 2 ig s a zA Z0 9 _ a zA Z0 9 1 amp 64 2 ig EOT will do that transformation for all HTML files in your directory More sophisticated methods hide an email address in JavaScript or use a CAPTCHA 120 perl a simple example Generate a list of email addresses of everyone on the Computer Lab s People web page sorted by surname Example input lt tr gt lt td gt lt a NAME asa28 gt asa28 lt a gt lt td gt lt td gt FE04 lt td gt lt td gt 63622 lt td gt lt td gt lt td gt lt td gt lt td gt lt td gt lt a HREF users asa28 gt Abrahams Alan lt a gt lt td gt lt tr gt lt tr gt lt td gt lt a NAME mha23 gt mha23 lt a gt lt td gt lt td gt FE22 lt td gt lt td gt 63692 lt td gt lt td gt lt td gt lt td gt lt td gt lt td gt lt a HREF users mha23 gt Allen Williams Mair lt a gt lt td gt lt tr gt lt tr gt lt td gt lt a NAME sa333 gt sa333 lt a gt lt td gt lt td gt GC33 lt td gt lt td gt 63680 lt td gt lt td gt lt td gt lt td g
48. out Use option rn m to retrieve earlier revisions There must not be a writable working file already gt co l example Fetches the latest revision as a locked writable file if the lock is available 57 svn Subversion Subversion is a popular centralized version control system 2001 Main advantages over RCS gt Supports a copy modify merge workflow RCS lock modify unlock This allows team members to edit the same files concurrently e Concurrent edits in different lines gt merged automatically e Concurrent edits in the same lines gt requires manual resolution of conflicts gt Manages entire directory trees not just single files gt Understand tree edits file copy delete rename move gt Supports several remote access protocols WebDAV ssh etc Full documentation http svnbook red bean com and http subversion apache org Microsoft Windows Subversion GUI http tortoisesvn tigris org 59 RCS Revision Control System cont d gt rcsdiff example Show differences between working file and latest version in repository use option rn m to compare older revisions Normal diff options like u can be applied gt rlog example Show who made changes when on this file and left what change comments If you want to use RCS in a team keep all the v files in a shared repository directory writable for everyone Team members have their own respective working
49. p D irectory to navigate document tree Emacs search function Ctrl S and finally Q uit gt Check usr share doc and Web for further documentation Examples of Unix tools cont d telnet ftp rlogin finger talk ping traceroute wget curl ssh scp rsync hostname host ifconfig route network tools xterm VT100 terminal emulator tar cpio compress zip gzip bzip2 file packaging and compression echo cd pushd popd exit ulimit time history builtin shell commands fg bg jobs kill builtin shell job control date xclock clocks which whereis locate command file clear reset clear screen reset terminal stty configure terminal driver display ghostview okular graphics file viewers xfig tgif gimp inkscape graphics drawing tools topnm pnmto cd jpeg graphics format converters be calculator passwd change your password chmod change file permissions lex yacc flex bison scanner parser generators 11 Examples of Unix tools man apropos xman info help documentation browser more less plaintext file viewer ls find list traverse directories search cp mv rm touch ln copy move rename remove renew files link shortcut files mkdir rmdir make remove directories cat dd head tail concatenate split files du df quota rquota examine disk space used and free ps top free uptime w process table and system load vi emacs pico interactive editors cc gcc C compiler
50. ress Ctrl Z 6 Stopped ghostview bg kill 6 29 Shell variables Serve both as variables of type string in shell programming as well as environment variables for communication with programs Set variable to value variable value Note No whitespace before or after allowed Make variable visible to called programs export variable export variable value Modify environment variables for one command only variablei value variable2 value command set shows all shell variables printenv shows all exported environment variables 31 Job control cont d A few more job control hints gt kill 9 sends SIGKILL to process Should only be used as a last resort if a normal kill which sends SIGINT failed otherwise program has no chance to clean up resources before it terminates gt The jobs command shows only jobs of the current shell while ps and top list entire process table Options for ps differ significantly between System V and BSD derivatives check man pages gt fg or just runs previously stopped job in foreground which allows you to switch between several programs conveniently 30 Standard environment variables lian gt HOME Your home directory also available as gt USER LOGNAME Your login name gt PATH Colon separated list of directories in which shell looks for commands e g bin usr bin usr X11R6 bin Should never contain
51. rguments of the shell command provided to exec 51 chmod set file permissions v Unix file permissions 3 x 3 2 1 12 bit information v Read write execute right for user group other gt set user id and set group id elevated execution rights v sticky bit only owner can delete file from directory gt chmod ugoa rwxst files Examples Make file unreadable for anyone but the user owner Is l message txt E i S 1 mgk25 private 1527 Oct 8 01 05 message txt chmod go rwx message txt Is l1 message txt i ssa 1 mgk25 private 1527 Oct 8 01 05 message txt For directories execution right means right to traverse Directories can be made traversable without being readable such that only those who know the filenames inside can access them 50 Some networking tools gt wget url Fetch a file over the Internet via HTTP or FTP Option r fetches HTML files recursively option 1 limits recursion depth gt ssh user hostname command Log in via compressed and encrypted link to remote machine If command is provided execute it in remote shell otherwise go interactive Preserves stdout stderr distinction Can also forward X11 requests option X or arbitrary TCP IP ports options L and R over secure link gt ssh keygen t dsa Generate DSA public private key pair for password free ssh authentication in ssh id_ds
52. s The Unix shell make project builder cmp diff patch compare files apply patches FCs cvs Svi git hg bzr revision control systems adb gdb debuggers awk perl python tcl scripting languages m4 cpp macro processors sed tr edit streams replace characters sort grep cut sort search lines of text extract columns nroff troff tex latex text formatters mail pine mh exmh elm electronic mail user agents 10 gt The user program that Unix starts automatically after a login gt Allows the user to interactively start stop suspend and resume other programs and control the access of programs to the terminal gt Supports automation by executing files of commands shell scripts provides programming language constructs variables string expressions conditional branches loops concurrency gt Simplifies file selection via keyboard regular expressions file name completion gt Simplifies entry of command arguments with editing and history functions gt Most common shell sh developed 1975 by Stephen Bourne modern GNU replacement is bash Bourne Again SHell 12 Unix inter process communication mechanisms invocation return value command line arguments sockets environment variables current directory shared memory i files and pipes semaphores standard input output error signals messages aa resource limits umask priority execution ti
53. s in C esac n The builtin command test expr which can also be written as Matches expanded word against each pattern in turn same I expr evaluates simple Boolean expressions on files such as matching rules as pathname expansion and executes the e file is true if file exists corresponding list when first match is found Example d file is true if file exists and is a directory case command in f file is true if file exists and is a normal file start r file is true if file exists and is readable app_server amp w file is true if file exists and is writable processid sa x file is true if file exists and is executable stop or strings such as kill processid x string1 string2 string1 lt string2 echo unknown command string1 string2 string1 gt string2 esac 37 38 Boolean tests examples Aliases and functions if e HOME rhosts then Aliases allow a string to be substituted for the first word of a command echo Found rhosts alias dir ls la mail LOGNAME s Hacker backdoor dir fi Shell functions are defined with name list In the function body the command line arguments are available as 1 2 3 etc The variable contains all arguments and their number Note A backslash at the end of a command line causes end of line to be ignored if hostname python cl cam ac uk then
54. set exported variable values and trigger any activity that you want to happen at each login Any subsequently started bash will read bashrc instead which is where you can define functions and aliases which unlike environment variables are not exported to subshells 43 Readline Interactive bash reads commands via the readline line editor library Many Emacs like control key sequences are supported such as vY vY YV vV Vv Vv y Ctrl A Ctrl E moves cursor to start end of line Ctrl K deletes kills the rest of the line Ctrl D deletes the character under the cursor Ctrl W deletes a word first letter to cursor Ctrl Y inserts deleted strings ESC performs history expansion on current line ESC turns current line into a comment Automatic word completion Type the Tab key and bash will complete the word you started when it is an existing variable user hostname command or filename depending on the context If there is an ambiguity pressing Tab a second time will show list of choices 42 Desktop environment startup Login process on the console of a desktop computer gt The X server provides access to display keyboard and mouse for X client applications via the X11 protocol After boot the system starts the X display manager xdm kdm lightdm etc which starts the X server via a root shell script etc X11 xdm Xservers The xdm then acts as the first X cl
55. t start a new branch master which diverges from the existing commit startpoint git Drench updates i TEIE git checkout updates 1 0 gt git checkout branchname switch the content of the working Switched to branch updates 1 0 directory to branch head branchname in preparation for working on echo c date Y M Kuhn gt gt filel that branch Points HEAD at the new branch head and updates git commit a m copyright notice added working files and index accordingly Commits will now be added to updates 1 0 c1f332c copyright notice added that branch 1 file changed 1 insertion git checkout master gt git checkout b branchname startpoint start a new Switched to branch master branch head then perform checkout on it git merge updates 1 0 Short for git branch followed by git checkout Auto merging filet Merge made by the recursive strategy gt git merge commit Merge one or more other branches into ee 7 p oY the current one Identifies all ancestors of the listed commit s e g branch names that are not yet ancestors of HEAD and tries to apply their changes to HEAD then make a new commit with all the listed commits as parents May require manual resolving of conflicts 1 file changed 1 insertion 83 84 git checkout updates 1 0 Switched to branch updates 1 0 sed i s nice very nice filet git commit a m nice gt very nice updates 1 0 cb87e76 nice gt very nice 1
56. t lt td gt lt td gt Allott Stephen lt td gt lt tr gt Example output Alan Abrahams lt asa28 cl cam ac uk gt Mair Allen Williams lt mha23 cl cam ac uk gt Stephen Allott lt sa333 cl cam ac uk gt perl email header parsing example Email headers as defined in RFC 822 have the form header lt lt EOT From Ian Grant cl cam ac uk 21 Sep 2004 10 10 18 0100 Received from ppsw 8 csi cam ac uk 131 111 8 138 by mtat cl cam ac uk with esmtp Exim 3 092 1 id 1V9afA 0004E1 00 for Markus Kuhn cl cam ac uk Tue 21 Sep 2004 10 10 16 0100 Date Tue 21 Sep 2004 10 10 05 0100 To Markus Kuhn cl cam ac uk Subject Re Unix tools notes Message ID lt 514FGFED mailVJ3982Y cl cam ac uk gt EOT This can be converted into a Perl hash table as easily as header s n s g fix continuation lines hdr FROM gt split S s m header and accessed asin if hdr Subject Unix tools 121 123 perl a simple example Possible solution usr bin perl url http www cl cam ac uk UoCCL people directory html open HTML wget 0 url die Can t start wget n while lt HTML gt if lt tr gt lt td gt lt a name wt gt lt tr gt i crsid 1 if lt td gt lt a href gt 7 lt gt C 7 lt gt lt a gt lt td gt lt tr gt i email crsid 3 2 lt crsid cl cam ac uk gt surname crsid
57. trees Its command line interface closely follows that of CVS but improves and simplifies the latter in many ways In particular Subversion gt understands renaming moving copying and replacing of both files and entire directory trees no per file version numbers gt understands symbolic links gt performs atomic commits gt versioned metadata MIME types EOL semantics etc gt is easy to learn and understand for current CVS users gt simpler branching and tagging through efficient copying gt more efficient transactions more disconnected operations gt wider choice of remote access protocols WebDAV ssh etc Old RCS CVS repositories can easily be converted http cvs2svn tigris org svn directory edits gt svn add filenames Put new files folders under version control Warning adding a directory adds all content as well unless you use svn add N dirnames gt svn delete filenames Delete files folders gt svn copy source destination Copy files folders gt svn move source destination Move files folders The above four operations will not transfer the requested changes to the repository before the next commit however the delete copy move operations perform the requested action immediately on your working files Remember not to use rm cp mv on working files that are under Subversion control otherwise these operations will not be reflected in the repository after your next commit If
58. well as a diff3 style file that shows the differing lines next to each other for convenient editing 65 svn a working example User 1 User 1 creates a repository opens a working directory and adds a file f svnadmin create HOME example svn repo f svn checkout file HOME example svn repo wd1 Checked out revision 0 B cd wdi ls AF svn svn status echo hello world gt filel svn status filet svn add filel A filet svn commit m adding my first file Adding filet Transmitting file data Committed revision 1 eek svn status 67 svn some more commands gt svn resolved filenames Tell Subversion you have resolved a conflict Also cleans up the three additional files gt svn revert filenames Undo local edits and go back to the version you had at your last checkout commit or update gt svn ls filenames List repository directory entries gt svn cat filenames Output file contents from repository Use svn cat filenames rev to retrieve older revision rev Some of these commands can also be applied directly to a repository without needing a working directory In this case specify a repository URL instead of a filename svn copy file HOME SVN trunk file HOME SVN tags release 1 0 An svn copy increases the repository size by only a trivial amount independent of how much data was copied Therefore to give a particular version a symbolic name simpl
59. wly added line gt patch lt diff file Apply the changes listed in the provided diff output file to the old files named in it The diff file should contain relative pathnames If not use option pn to strip the first n directory names from pathnames in diff file If the old files found by patch do not match exactly the removed lines in a u diff output patch will search whether the context lines can be located nearby and will report which line offset was necessary to apply them gt diff3 myfile oldfile yourfile Compare three files and merge the edits from different revision branches 56 RCS Revision Control System Operates on individual files only For every working file example an associated RCS file example v keeps a revision history database RCS file RCS example v RCS files can be kept next to the working files or in a subdirectory RCS Wi co ci gt ci example Move a file back into the RCS file as the new latest revision check in Working file gt ci u example Keep a read only unlocked copy _ 2m Pte ci 1 is equivalent to ci followed by co gt ci l example Keep a writable locked copy only one user can have the lock for a file at a time ci 1 is equivalent to ci followed by co 1 gt co example Fetches the latest revision from example v as a read only file check
60. ws Linux g Delete all lines that do not end with OK command d delete sed OK d Print only lines between those starting with BEGIN and END inclusive sed n BEGIN END p Substitute in lines 40 60 the first word starting with a capital letter with an sed 40 60s A Z a zA Z X 48 grep head tail sort gt Print only lines that contain pattern grep pattern files Option v negates match and i makes match case insensitive gt Print the first and the last 25 lines of a file head n 25 file tail n 25 file tail f outputs growing file gt Print the lines of a text file in alphabetical order sort file Options k select column n sort numbers u eliminate duplicate lines r reverse order 49 find traverse directory trees find directories expression recursively traverse the file trees rooted at the listed directories Evaluate the Boolean expression for each file found Examples Print relative pathname of each file below current directory find print Erase each file named core below home directory if it was not modified in the last 10 days find name core mtime 10 exec rm i The test mtime 10 is true for files older than 10 days concatenation of tests means logical and so exec will only be executed if all earlier terms were true The is substituted with the current filename and terminates the list of a
61. y svn copy it in the repository into a new subdirectory of that name 66 svn a working example User 2 User 2 checks out own working directory and start working on it f svn checkout file HOME example svn repo wd2 A wd2 filet Checked out revision 1 B cd wd2 ls AF svn filet svn status echo hello dogs gt file1 svn status M filel 68 svn a working example User 1 Meanwhile User 1 also adds and changes files and commits these ls AF svn filet cat file hello world echo bla gt file2 svn add file2 A file2 echo hello humans gt filet svn status M filet A file2 svn commit m world gt humans Sending filel Adding file2 Transmitting file data Committed revision 2 svn status 69 svn a working example User 2 cat filel lt lt lt lt lt lt lt imine hello dogs hello humans gt gt gt gt gt gt gt r2 svn status filei mine file1 r1 file1 r2 C filel echo hello humans and dogs gt filel svn resolved filel Resolved conflicted state of filei svn status M filet svn commit m k9 extension Sending filel Transmitting file data Committed revision 3 71 svn a working example User 2 User 1 managed to commit her changes first so User 2 will be notified of a concurrent editing conflict and will have to merge the two changes svn commit m world gt dogs Sending file1 svn E155011 Commit failed det
Download Pdf Manuals
Related Search
Related Contents
HeartSine 350P - Trainer User Manual プロトコール Voyager with Unicode System Administration User's Guide Samsung E848 18K Gold User Manual The Huygens Essential User Guide 上手に節電するためー - 日立の家電品 「もんじゅ」の設備健全性確認と 保全計画について User Manual CONAC-446 instalacio.. Copyright © All rights reserved.
Failed to retrieve file