540 likes | 677 Views
Pablo Manalastas <pmanalastas@ateneo.edu> Dep't of Info. Systems & Computer Science Ateneo de Manila University. INTRODUCTION TO UNIX/LINUX. GNU/LINUX. GNU/Linux – consists of Linux OS kernel, GNU utilities, and open source and commercial applications.
E N D
Pablo Manalastas <pmanalastas@ateneo.edu> Dep't of Info. Systems & Computer Science Ateneo de Manila University INTRODUCTION TO UNIX/LINUX
GNU/LINUX • GNU/Linux – consists of Linux OS kernel, GNU utilities, and open source and commercial applications. • A Unix-workalike – multi-user, multi-tasking, networking operating system, with several choices of graphical user environments, office suites, and other applications. • Very stable/robust yet free -- both binaries and sources available as free downloads from the Net. • Kernel written by Linus Torvalds & company. Utilities are from FSF/GNU, BSD, etc.
Windows-Linux Comparison • Windows runs Microsoft Office and lots of games; is perceived to be easy to install and configure; is notoriously unstable; performs poorly; crashes are frequent. • Linux runs OpenOffice, scores of technical software and fewer games; can be tricky to install and configure; is rock solid; performs impeccably; crashes are extremely rare.
LEARNING LINUX • Linux gives you power, but it takes some time to learn how to harness it. • To be proficient with Linux read the documentation (FAQs, HOWTOs, and user guides from www.linuxdoc.org) and use it regularly for at least for a few months. • Join local user groups like the Phil. Linux Users' Group (plug-request@lists.q-linux.com).
TYPING COMMANDS • At the Unix prompt, a user may type a command using the following format:commandname -option --arguments • The commandname, options, switches, and arguments are separated from each other by one or more white spaces (blanks or tabs). • The intention is to have the command work on the supplied arguments. • The options or switches modify the standard behaviour of the command. • Example: ls -l /var/log/messages
Creating a User Accountand Logging In • Unless needed, do not use the system as the super-user (root); as root, create an account for yourself as a normal non-root user:adduser login_nameYou will be asked to supply a password. • Log out as root, and then log in as a normal user. This way you can practice as much as you want without danger of damaging the system.
HOW TO QUIT LINUX • To log out without switching off the computer:logout • To switch off the computer:shutdown -h -t0 nowThen push the OFF button. • To reboot the computer:shutdown -r -t0 nowctrl-alt-delete • Under X-window:ctrl-alt-backspace then ctrl-alt-delete
GETTING HELP • Help from the Net:“Linux installation and getting started” guide (http://www.linuxdoc.org/gs/gs.html)“Linux FAQ” (http://www.linuxdoc.org/FAQ/Linux-FAQ/) • Online help:man commandinfo commandwhereis commandapropos command • What commands have manual pages available?ls /usr/man/man1
Files • Programs, data, and hardware devices are all represented as files in a Unix system. • Each file is identified by name, and files are hierarchically arranged in directories, which are also files. • For security reasons, each file belongs to an owner and a group. • The owner, the group, and the rest of the world may be selectively given read, write, and execute permissions to the file by the owner or by the super-user root.
File Types • “-” Regular files: executable programs, text files, data files, shared libraries. • “d” Directories: contains named references to other files. • “c” and “b” Character device files and block device files. • “l” Symbolic links: A file that contains a pathname; the file referenced by the pathname may or may not exist. A hard link is another directory entry for a file that exists in the same partition.
PATHNAMES • Pathname – the name of a file, together with the names of directories and subdirectories in which it is contained. • Absolute pathname – the pathname of a file, relative to the root directory “/”. Example,/var/spool/mail/pmana • Relative pathname – the pathname of a file, relative to the current working directory. Example, linux/include/linux/version.h
Filesystem Standard (FSSTND) • FSSTND – names of common directories and what files are contained in each. • /bin and /sbin – executables needed at boot time./boot – contains the Linux kernel and boot data./dev – contains device files./etc – contains the system configuration files./home and /root – home directories of users./lib and /usr/lib – contains the shared libraries./proc – contains info about running processes./tmp and /var/tmp – directory for temporary files./usr/bin and /usr/sbin – contains executables./var – contains data files for reading/writing./opt – contains optional packages.
Shell Shortcut Keys • /bin/sh or /bin/bash – the Bourne (again) shell program; accepts commands typed in by the user and causes the execution of those commands. • bash history keys: UP, DOWN, LEFT, RIGHT • bash filename completion key: TAB
Setting the Terminal Right • Selecting the correct terminal typeTERM=linuxTERM=consoleTERM=vt100TERM=xtermexport TERM • Clearing the terminal screenclear • Resetting when terminal goes crazyreset
Creating and Viewing Text Files • Use a text editor to create a text file.ed filenamevi filenameemacs filenamejoe filenamenedit filename • Viewing the contents of a text filecat filenamemore filenameless filename
What Files Are Out There? • The ls command lists names of files in the current working directory or lists names of files that satisfy a given name pattern. • ls list names of all files in current directoryls pattern list only files that satisfy patternls -a list all files, including hidden filesls -l list long, with types, owners, permissionsls -t list most recent firstls -u list by time last usedls -F list by file type
Renaming, Moving, Copying, and Deleting Files • mv oldnewrename old to new.mv file/dir move file to new loc /dir.cp origduplic copy file orig to file duplic.cp -a /dir1/dir2 copy entire directory to /dir2.rm -f file forcibly delete file; will not ask for confirmation.rm -rf /dir recursively delete directory /dir and all its contents
Counting, Searching, Sorting Files • wc -lwc file counts lines, words, characters in file • grep -v pattern fileprints all lines of file that does/doesn't contain pattern. • sort -r filesorts file in increasing/reverse order.
Showing Parts of Files • head -n file prints the first n lines of file.tail -n file prints the last n lines of file. • cut -cJ-K file prints all characters in column positions J-K of file. • cut -dD -fJ-K fileprints all fields in field positions J-K in file, using character D as field delimiter
Comparing and Patching Files • cmp file1 file2show location of first difference between file1 and file2 • diff file1 file2show all differences between file1 and file2 • diff -NuR file1 file2show all differences between file1 and file2 in “patch” format • patch -p0 <diffspatch files using the supplied diffs
Misc File Commands • Creating symbolic links:ln -s targetfilename symlinknameTarget file need not exist • Creating hard links, another name for a file that already exists in the same partition:ln existingfile newfilename • Creating an empty file or updating a file's date:touch filename
Using Hardlinks • To create a useful alternate name for a program • Example/usr/sbin/sendmail/usr/sbin/newaliasesare hardlinks to the same file
Working with Directories • pwd print working directory. • cdmake your home directory the working directory. • cd dirnamemake dirname the working directory. • mkdir dirnamecreate a new directory dirname in the current working directory. • rmdir dirnameremove the empty directory dirname.
File Permissions • chmod – change permissions to a filechmod 640 myfile • chown – change owner of a file (/etc/passwd)chown owner.group myfile • chgrp – change group of a file (/etc/group)chgrp grpname myfile • umask – set the file creation mask(what are not allowed)umask 022
Functions of the Shell • The shell program /bin/sh accepts commands typed by the user and causes the execution of those commands. It is the go-between the user and the facilities of the Unix kernel. • Some of its functions are:Filename completion – you supply a pattern and the shell gets all files that fit the pattern;I/O redirection & Pipes– you can arrange for input to/output from a program to be redirected to files, and for execution of pipes; Personalizing environment – you can define your own commands, shortcuts, variables, etc.
Filename Generation with Wildcards • The shell is capable of generating filenames in the target directory that match given patterns. • ? - matches a single character (not a leading .)Example: ls -l chapter? • [ ] - matches one character from the given rangeExample: ls -l chapter[0-9][0-9] • * - matches zero or more characters (except a leading .)Example: ls -l chapter*
Redirecting Stdout and Stderr • The standard output of a program (normally to the screen) can be redirected to a file using the symbol “>”. Example:sort /etc/passwd /etc/group > namesThe “>>” symbol is used to append to a file:cat /usr/src/linux/COPYING >> names • The standard error output of a program (normally to the screen) can be redirected to a file using the symbol “2>”. Example:gcc sample.c -o sample 2> error.log • We can combine these:sort /usr/dict/american.med >words 2>&1
Redirecting Stdin • The standard input to a program (normally the keyboard) can be redirected to come from a file. Examples:sort < fruitsmailx -s “Hello” juan pablo jose < myletter • Some or all of stdin, stderr, and stdout can be redirected in the same command. Examplesort < fruits > sortfruits 2> sorterr.log
Multitasking with Pipes • A pipe is a way to connect the output of one program to the input of another without any user-created temporary file; a pipeline is a connection of two or more programs through pipes. • All the programs in the pipeline are started at the same time and the system multitasks to give a fair share of CPU time to each program. • Example:cat /usr/dict/american | grep “aa” | sort
Multitasking: Background Processes • To run a time-consuming program in the background:program arguments & • To run in the background even after loggin out:nohup program arguments & • To check the PID of processes that are running:ps ax • To stop a running process:kill -9 PID
Shell Variables • Shell variable – a user-defined variable name usable in the current shell. • Assigning values to shell variables:cellnumber=”+63-917-8338785”webpage='xhttp://currry.ateneo.net/' • Reading input from stdin:read nameread cellnumber
Environment Variables • Env variable – a variable name that is usable in the current shell and in all children processes of this shell. • Examples:EMAIL='pmanalastas@ateneo.edu'CARPLATE=XJW889read REGNUMexport EMAIL CARPLATE REGNUM • The export command turns a shell variable to an env variable. Env variables are inherited by children processes from their parent process.
System defined Environment Variables • Some environment variables are pre-defined by the system. • Examples:PATH – list of directories searched when system looks for a commandTERM – name of terminal that is currently in usePS1 PS2 – primary and secondary promptsHOME – user's home directoryLOGNAME – user's login nameSHELL – user's shell program
Using Variables • To access the value of a variable use the prefix $ or ${ }. • To display the value of a variable:echo $PATHecho ${CARPLATE} • Variables may be used as command name or argument:cp $file ${file}02$CC myprog.c -o myprog
Command Substitution • To access the output of a program use $(program) or `program`. Both forms may be double quoted as in“$(program)” or “`program`” • Exampleslogin=$(cat /etc/passwd | grep Mana | cut -d: -f1)echo ${login}today=`date | cut -d\ -f1-2`echo $todayecho ${today} > /tmp/today.txt
Quoting • The following characters have special meaning for the shell: space & < > $ * ' “. If you want to use them as is, quote with \. • Examples:mkdir My\ Documentscat Jack\&Jillecho \<html\> • Single quotes suppresses the special meanings:askdad='allowance $100.00 & trans $20.00' • Double quotes will not supress meaning of $:PATH=”$PATH:/home/pmana/bin”
Quoting Exercise • abc=”xyz”What's the result of:echo “$abc”echo $abcecho '$abc'echo \$abc
Tailoring Your Environment • Values of environment variables that you want to stay in effect every time you log in should be saved in the file $HOME/.profile • Example /home/pmana/.profilePATH=”$PATH:/home/pmana/bin”PS1='$(pwd)\$ 'export PATH PS1 • To put into effect now your new .profile file:. .profile
Shell Scripts • Script – one or more lines of Unix commands in a text file, saved as an executable file.Use “chmod +x file”, to make file executable.Example:#!/bin/shtoday=”$(date)”tyme=”$(echo $today | cut -c12-13)”if [ “$tyme” -lt 12 ]; then echo “Good morning.” ;elif [ “$tyme” -lt 18 ]; then echo “Good afternoon.” ;else echo “Good evening.” ;fi
Scripts: Command-Line Arguments • If the command isgcc myprog.c -o myprogthen$0 = gcc$1 = myprog.c $2 = -o$3 = myprog • These variables $0, $1, $2, etc can be used within shell scripts
Scripts: More About Command-Line • $#number of command line arguments$0 not included • $*$@all command line arguments as one string • $?the return value or exit code of the previouscomand
Exit Code or Return Valuesof Programs • When a program finishes, the exit code or return value can be tested in a shell program. Exit codes are as follows:zero(0) normal program terminationnon-zero abnormal program termination; program exited with error
Scripts: Command Lists • Executing commands in the backgroundcommand & • Executing commands one after anothercommand1; command2; command3 • Execute command2 if command1 exits normallycommand1 && command2 • Execute command2 if command1 exits abnormallycommand1 || command2
Scripts: If construct • if command1; then command2; fi • if command1then command2fi • if command1; then command2else command3fi
Scripts: If example • read ansif [ “$ans” = “y” ]; then echo “Your answer is yes”else echo “Your answer is not yes”fi • The construct [ ] is equivalent to thetest command
Scripts: Complicated If • if command1; then command2elif command3; then command4elif command5; then command6else command7fi
Scripts: Case construct • case WORD in(PATTERN) COMMANDLIST ;; (PATTERN) COMMANDLIST ;; (PATTERN) COMMANDLIST ;; esac
Scripts: For construct • for NAME in{ WORDS }; do COMMANDSdone
Scripts: While consruct • while TEST-COMMANDS; do CONSEQUENT-COMMANDSdone
Scripts: Until construct • until TEST-COMMANDS; do CONSEQUENT-COMMANDSdone