Download int_unix - Pablo Manalastas, PhD

Document related concepts

Unix wikipedia , lookup

Smallfoot wikipedia , lookup

Acorn MOS wikipedia , lookup

Security-focused operating system wikipedia , lookup

Library (computing) wikipedia , lookup

Windows NT startup process wikipedia , lookup

DNIX wikipedia , lookup

MTS system architecture wikipedia , lookup

RSTS/E wikipedia , lookup

Plan 9 from Bell Labs wikipedia , lookup

OS 2200 wikipedia , lookup

Spring (operating system) wikipedia , lookup

Commodore DOS wikipedia , lookup

Burroughs MCP wikipedia , lookup

Comparison of command shells wikipedia , lookup

CP/M wikipedia , lookup

Computer file wikipedia , lookup

VS/9 wikipedia , lookup

Unix security wikipedia , lookup

Transcript
INTRODUCTION TO UNIX/LINUX
Pablo Manalastas <[email protected]>
Dep't of Info. Systems & Computer Science
Ateneo de Manila University
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 ([email protected]).
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 Account
and 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_name
You 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 now
Then push the OFF button.
●
To reboot the computer:
shutdown -r -t0 now
ctrl-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 command
info command
whereis command
apropos 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 type
TERM=linux
TERM=console
TERM=vt100
TERM=xterm
export TERM
●
Clearing the terminal screen
clear
●
Resetting when terminal goes crazy
reset
Creating and Viewing Text Files
●
Use a text editor to create a text file.
ed filename
vi filename
emacs filename
joe filename
nedit filename
●
Viewing the contents of a text file
cat filename
more filename
less 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
ls
ls
ls
ls
ls
ls
list names of all files in current directory
pattern
list only files that satisfy pattern
-a
list all files, including hidden files
-l
list long, with types, owners, permissions
-t
list most recent first
-u
list by time last used
-F
list by file type
Renaming, Moving, Copying, and
Deleting Files
●
mv
mv
cp
cp
rm
old new
file /dir
orig duplic
-a /dir1 /dir2
-f file
rm -rf /dir
rename old to new.
move file to new loc /dir.
copy file orig to file duplic.
copy entire directory to /dir2.
forcibly delete file;
will not ask for confirmation.
recursively delete directory
/dir and all its contents
Counting, Searching, Sorting Files
●
●
●
wc -lwc file
counts lines, words,
characters in file
grep -v pattern file
prints all lines of file that
does/doesn't contain pattern.
sort -r file
increasing/reverse
sorts file in
order.
Showing Parts of Files
head -n file
tail -n file
prints the first n lines of 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 file
●
prints all fields in field
positions J-K in file, using
character D as field delimiter
Comparing and Patching Files
●
cmp file1 file2
show location of first difference between
file1 and file2
●
diff file1 file2
show all differences between file1 and file2
●
diff -NuR file1 file2
show all differences between file1 and file2
in “patch” format
●
patch -p0 <diffs
patch files using the supplied diffs
Misc File Commands
●
Creating symbolic links:
ln -s targetfilename symlinkname
Target 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/newaliases
are hardlinks to the same file
Working with Directories
●
pwd
print working directory.
●
cd
make your home directory the working
directory.
●
cd dirname
make dirname the working directory.
●
mkdir dirname
create a new directory dirname in the
current working directory.
●
rmdir dirname
remove the empty directory dirname.
File Permissions
●
chmod – change permissions to a file
chmod 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 range
Example: 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 > names
The “>>” 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 < fruits
mailx -s “Hello” juan pablo jose < myletter
●
Some or all of stdin, stderr, and stdout can be
redirected in the same command. Example
sort < 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 usercreated 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 name
read 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='[email protected]'
CARPLATE=XJW889
read REGNUM
export 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 command
TERM – name of terminal that is currently in use
PS1 PS2 – primary and secondary prompts
HOME – user's home directory
LOGNAME – user's login name
SHELL – 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 $PATH
echo ${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`”
Examples
login=$(cat /etc/passwd | grep Mana |
cut -d: -f1)
echo ${login}
today=`date | cut -d\ -f1-2`
echo $today
echo ${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\ Documents
cat Jack\&Jill
echo \<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
echo
echo
echo
“$abc”
$abc
'$abc'
\$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/.profile
PATH=”$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/sh
today=”$(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 is
gcc myprog.c
-o myprog
then
$0
$1
$2
$3
●
=
=
=
=
gcc
myprog.c
-o
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 previous
comand
Exit Code or Return Values
of 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 termination
non-zero
abnormal program termination;
program exited with error
Scripts: Command Lists
●
●
●
●
Executing commands in the background
command &
Executing commands one after another
command1; command2; command3
Execute command2 if command1 exits normally
command1 && command2
Execute command2 if command1 exits
abnormally
command1 || command2
Scripts: If construct
●
●
●
if command1; then command2; fi
if command1
then
command2
fi
if command1; then
command2
else
command3
fi
Scripts: If example
●
●
read ans
if [ “$ans” = “y” ]; then
echo “Your answer is yes”
else
echo “Your answer is not
yes”
fi
The construct [ ] is equivalent to the
test command
Scripts: Complicated If
●
if command1; then
command2
elif command3; then
command4
elif command5; then
command6
else
command7
fi
Scripts: Case construct
●
case WORD in
(PATTERN) COMMANDLIST ;;
(PATTERN) COMMANDLIST ;;
(PATTERN) COMMANDLIST ;;
esac
Scripts: For construct
●
for NAME in { WORDS }; do
COMMANDS
done
Scripts: While consruct
●
while TEST-COMMANDS; do
CONSEQUENT-COMMANDS
done
Scripts: Until construct
●
until TEST-COMMANDS; do
CONSEQUENT-COMMANDS
done
Programming in C
●
●
●
Edit text file (progname.c)
vi progname.c
Compile and link with needed libraries
gcc progname.c -o progname -lm
Steps can be automated using a Makefile. The
command to build the target is just
make
Example Makefile
●
CC=gcc -Wall -O2 -m386 -mcpu-i386
LFLAGS=-L/usr/motif/lib -lXm -lm -lncurses
myprog: myprog.o
gcc myprog.o -o myprog ${LFLAGS}
myprog.o: myprog.c myprog.h
${CC} -c myprog.c -o myprog.o
Unix System Calls
●
●
●
●
●
Layer between user and kernel
Lowest level of interaction with Unix (and
operating systems, in general)
Considered entry points to the kernel; facility
provided by the operating system
Everything built else built on top of them
Normally uses C language
System Call Categories
●
●
Process control (fork, exit, wait, waitpid,
exec, system)
File manipulation (open, close, lseek, read,
write, dup, fcntl, ioctl, stat, chmod,
chown, link, unlink, mkdir, rmdir, sync)
●
●
●
Signals (kill, sleep, abort, system)
Information maintenance (time(2), settimeofday,
gettimeofday)
Communications (pipe, popen, pclose,
mkfifo, msgctl, msgsnd, msgrcv,
semctl, shmctl)