Introduction to the Operating System UNIX (1)


UNIX is another operating system widely used today, besides Microsoft's Window Operating System.

UNIX originated from Bell Laboratories around 1970, and since then, has been widely used by many universities.

LINUX is a UNIX clone, (it is called Linux because "UNIX" is a patented name). LINUX was written by a Finnish Computer Science student, Linus. He wrote it as a project under his teacher, and he put it in the Internet for everyone to download.

People all around the world added to it, and especially the people from Free Software Foundation.

LINUX usually comes free when you purchase books on LINUX. My LINUX comes from a book published in Taiwan, which includes LINUX CDROM for around HK$120.

LINUX includes many softwares : C, Fortran, Pascal, Perl, Bison, Flex, C++, .... One can learn a lot about computer from these. (It is my opinion that people learn computer the traditional way, i.e. learn how to write programs and NOT just learn how to use programs. One can learn Qbasic fast, and be able to program in a very short time. After that, he should learn C. After learning C, he will be fully equipped to master many many things in computer.)

Also, I assume that you know Qbasic, and have read my Qbasic web pages.

Installing LINUX on your computer may prove difficult for you, hence I would advise you ask someone to install it for you. Also I suggest you buy a used PC (one that uses 486 or up) solely for LINUX. (Though you do not have to buy another PC, but buy another hard disk instead, or use the same drive Window uses. But to boot Window and LINUX from one computer involves either LILO settings or BIOS settings, and may be difficult.)

From now you, I assume that you have access to LINUX (or UNIX) and C compiler, and you know how to log in , how to log out (or shutdown the system).


Difference between LINUX and WINDOW that you should know

In Window, we use A:, B:, C:, D:, .... to denote drives. But in Linux, it uses "hda, hdb, hdc, ..." to means "hard disk A, hard disk B, ..." "fd0, fd1" to mean "floppy disk drive 1, floppy disk drive 2". Also the pathname for files are different,

(WINDOW)c:\windows\applications\dir1\filea
(LINUX)/home/robert/dir2/fileb

One uses backward slash and one forward slash.

Commands or filenames under DOS are not case-insensitive, (i.e. small or capital letter does not matter), but LINUX is case sensitive ! e.g. "reportfile" is not the same as "Reportfile".


Comparison of DOS commands and LINUX commands


DOSLINUX
cls clear or reset
Clears the screen "Clear" just clears the screen, but "reset" does more. It resets the terminal parameters. This command is especially useful when your program fails in an unexpected way, and the display is totally garbage (or even what you type in could not be displayed correctly), then you press "Ctrl + c" , and type "reset". The screen will usually be restored normal.
"Ctrl + c" (=cancel) is the first command to learn. It will stop the running program.
date date
Display the date.
(Note that there is a "time" command in DOS, but "time" in UNIX is different.
In Unix, "time binaryfile" will executes the "binary file", and show how much computer time it uses (in second).
Same
cd dirname cd dirname
Change the directory Same. e.g.
cd /home/robert/dir1
Note that we may use absolute pathname or relative pathname too. e.g. If we are currently in "/home/robert/", then we may just use
cd dir1


cd ..
Change up one level, change to "parent" directory.

If you do not know "absolute path name", "relative pathname", you should read my Qbasic webpages.

md dirname mkdir dirname
Make a new directory under current directory Same
dir filename vdir filename
List the files under current directory. Same.

Note that we may use "wildcard" too, e.g.
vdir prog*
all files whose name starts with "prog" will be listed.
vdir *.c
all files whose extension is ".c" will be listed.
vdir ab*pl
all files whose name starts with "ab" and ends with "pl" will be listed.
"vdir" will list many information. To get a shorter listing, use "ls filename". (ls = list)

type filename cat filename
Display content of file on screen. We may use "piping" too. Same. For piping, it is
cat filename | more
(Note : "cat" = "catenate", and it orginates from

cat file1 file2 ... filen > destinfile

Now "file1 ... filen" will not be displayed on the terminal, but appended together into "destinfile".
I remember "cat filename" as "catalogue filename.)
copy file1 file2 cp file1 file2
cp file1 file2 ... filen dirname
Copy content of "file1" onto "file2". Original content of "file2" will be lost. Same.

UNIX has another form, e.g.
cp * /home/tom/dir1/
will copy all files in the current directory to directory "/home/tom/dir1/".
move file1 file2 mv file1 file2
mv file1 file2 .... dirname
Copy content of "file1" onto "file2". After that "file1" will be deleted. Original content of "file2" will be lost. Same.

Unix has another form, e.g.
mv prog{1,2,3}.c /home/john/dir2/
will move prog1.c, prog2.c, prog3.c to directory "/home/john/dir2/". Note the use of curly brackets for "expansion".
mv *c /tmp/abc/
will move all files whose names end with "c" to directory "/tmp/abc/".
del filename rm filename
Deletes the file "filename" Same. (Note : "rm" = "remove")

e.g.
rm abc*
will remove all files whose name start with "abc".
rd dirname rmdir dirname
Remove (or delete) the directory "dirname". Same. Notice that "dirname must be empty before you can delete it.
rename file1 file2 mv file1 file2
Change the name of "file1" into "file2". There is no "rename" command in UNIX, but "mv" serves the same.
exit exit
logout
Exit the operating system In Unix, we may use "exit" or "logout". But if you are the only person using the computer, then when you leave, you should shut down the system with the command,

shutdown -h now

Then wait for the computer to "halt everything". Then it would be safe to turn off power. It is the same as in WINDOW, you cannot just turn off power, because files may be lost (opened files would usually be in memory and not in the hard disk. Hence any changes you made will be lost, if you simply turn power off).

Some Common UNIX Commands

free
This shows how much memory has been used, and how much is available.
df
[Disk Free] This shows the amount of free disk space. e.g. 27% used....
du filename
[Disk Usage] Shows the amount of disk storage in Kbytes filename uses.
May also use "wildcard" character, e.g.
du *
(List the size of all files)

du *.c
(List the size of all files whose name ends with ".c" in Kbytes).

du ab*cd
(List the size of all files whose name begins with "ab" and ends with "cd")

du record1 filea
(List the size of the two files, "record1" and "filea")
file filename
Shows what type of file "filename" is : ASCII file, executable binary file, ... May also use wildcard character, e.g.
file *
(Show the type of all files in current directory)

file chap{1,2,3}
(Show the type of files of "chap1, chap2, chap3". Note the use of curly brackets and comma.)
diff file1 file2
[Difference] This shows the difference between 2 files, "file1" and "file2".
head filename
Type the first 10 lines of "filename" on screen. e.g.
head prog.c
(Type out 10 lines of "prog.c")

head -20 prog.c
(This types 20 lines, "-20" is "option". All "options" begin with "-" in UNIX.)
tail filename
Type the last 10 lines of "filename" on screen. e.g.
tail prog.c
(Type out last 10 lines of "prog.c")

tail -15 prog.c
(This types last 15 lines.)
wc filename
[Word Count] This shows the "no of lines, no of words, no of characters" filename has. May also use wildcard. e.g.
wc *
(Shows the "word count" of all files in current directory.)

wc abc{1,2,3}.c
(Shows the word count of "abc1.c abc2.c abc3.c")
man commandname
[Manual] This is similar to "help" in Window. This is very important, because we can learn a lot about particular "command", or "C library subroutines", ... e.g.
man reset (Shows how to use the command "reset".)
We may use the cursor movement key (up, down) to scroll up or down.

To quit, we type "q". (ctrl + C to quit will not work here).

apropos keyword
This will show all the commands available in the system that has connection with "keyword", e.g.
apropos compiler
will show all commands relating to compiler.
pwd
[Path to Working Directory] This shows the "absolute pathname" of the directory you are currently in, e.g. it will show
/home/robert/dir1/subdir2/
passwd
passwd [userid]
This changes the password. The second form is for "super-user" who logs in as "root". He may change the password of any user.
w
[w, or who] This shows all users currently logged in.
echo $?
"$?" is a system variable. If the previous command (or program just run) is successful, it will show 0. If it fails in some way, or there are errors, it will show value other than 0.
"echo" may also be used to show other system variables.

These commands will suffice for most purposes, and you may learn more later.


How to use the editor "emacs"

"emacs" is the editor we will be using to write C programs. It is not as intuitive as "Notepad", and you will have to be patient and get used to it gradually. ( Also notice that many commands begin with "ctrl + x".)

emacs
This is the command to activate the editor.
ctrl + x -> ctrl + f (it means : first pressing "ctrl" and "x" together, THEN, pressing "ctrl" and "f" together.)
Open file. You will be asked to enter the filename at the bottom row.
ctrl + x -> ctrl + r
Open file for READING only , no changes to the file will be made.
You will be asked to enter the filename at the bottom.
You should use this command when you investigate various files in your system. You should not change the content of the system files.
ctrl + x -> ctrl + v
Sometimes, we enter the wrong filename, and we would not know it until the file is displayed. Then pressing "ctrl + x -> ctrl + v" will allow us to re-enter the filename again.
ctrl + x -> ctrl + s
Save the content of the opened file.
ctrl + x -> ctrl + w
Save As. Save the content into another file. You will be asked the new filename.
ctrl + x -> ctrl + c
Exit "emacs".
ctrl + k
Editing is done the usual way. You use the 4 arrow keys to move left, right, up, or down, and use the "Delete", "<-" keys to erase.
"ctrl + k" will erase the whole line.( k = kill )
ctrl + shift + _ (underscore)
Undo. Sometimes we erase things we don't want to erase. This is the command to "undo".
ctrl + x -> ctrl + g
Abort the present command. Sometimes you press the wrong keys, e.g. you want to "save" the file, but press the keys for "save as", then you use this to abort. You should remember this command.
alt + shift + <
(The 3 keys are pressed together) Move to the beginning of file, same as "ctrl + Home" in "Notepad"
alt + shift + >
Move to the end of file, same as "ctrl + End" in "Notepad"
ctrl + s
Search. You will be asked the "string" to search. It will stop when it finds the first occurence. Pressing "ctrl + s" again, it will jump to the second occurence, and so on. Searching is from the current cursor position to the end of file.
ctrl + r
Reverse search. Searching is from the current cursor position back to the beginning of file. You will be asked the "string" to search. It will stop when it finds the first occurence. Pressing "ctrl + r" again, it will jump to the second occurence, and so on.
alt + x -> repl s -> Enter (That is, first pressing "Alt" and "x" together, then type in "repl s", then press "Enter".)
Global Replace. You will be asked the "string" to replace, and the "string" to replace it. Every occurences of it will be replaced.

WHAT YOU HAVE LEARNED NOW WOULD ALREADY SUFFICE FOR SIMPLE EDITING.

Try editing some files, then save it and exit "emacs" ("emacs", then "ctrl + x -> ctrl + f " filename, then editing, then "ctrl + x -> ctrl + s" to save, then "ctrl + x -> ctrl + c" to exit). When outside "emacs", use "cat filename" to display the file. Also you may try some other commands, e.g. delete the file, rename the file, copy it to another, or move it to another directory, ...
alt + shift + %
Query replace. We will be asked the "string" to be replaced, and the "string" to replace it. Whenever "emacs" finds a match, it will stop and wait for your instruction.
y yes, replace
n no. skip this one and continue
q quit
. Replace this one, and then quit
^ Go back to previous match
! Global replacement without further asking.

We will stop talking about "emacs" commands now, but will return to it later.


Compilation, Linking, ...

We will discuss the compilation process and the related Linux commands here.

First, we use "emacs" to enter a program, say

(File : psin.c)
      #include <stdio.h>
      #include <math.h>

      /*   This program prints the sin(x) from 0 to 90 degree    */

      int main()
      {   double x,y,z;
          for (x=0.; x<=90.; x+=1.)
               {y = x*3.1416/180.;
                z = sin(y);
                printf("%10.2f       %15.5f \n",x,z);
               }
       return 0;
       }
and have saved it in file "psin.c". Notice that all C program files should have extension ".c" in its name. To compile it, we issue the command,

gcc -Wall filename.c -lm
e.g.

gcc -Wall psin.c -lm

Here "gcc" is the "C Compiler" from Free Software Foundation. You will find that nearly all software from FSF begins with the letter "g". The "-Wall" is an "option" to the C compiler, meaning "Warning, all warning messages should be produced". "psin.c" is the file to be compiled. There is a "-lm". Here "-lm" means "to use library libm.a, which is a library containing Mathematics subroutines" (if the library file is "libvga.a", then you should specify "-lvga", e.g. "gcc -Wall psin.c -lvga". Notice that both "lib" and ".a" are stripped away when specifying library file name.)

This command
gcc -Wall filename.c -lm
is in fact two programs combined into one, "gcc" and "ld", the former is a "C Compiler" and the latter, a "link loader". We may also do it in two separate steps,

gcc -Wall -c psin.c
(The option "-c" means : "just compile the program". You will find that a file "psin.o" is produced.

There are "un-resolved references" in "psin.o", and you may view it with the command,
nm filename.o
e.g.

nm psin.o

You will notice that it prints all un-resolved references.

Next, "link edit" them with the "maths library",
gcc -Wall filename.o -lm
e.g.

gcc -Wall psin.o -lm

(Notice that we use "psin.o" and NOT "psin.c".)

This will produce a file "a.out". Then just typing this
a.out
will execute the program.

But at present, do not do this, but use "gcc -Wall psin.c -lm" and then run "a.out".

More about the "gcc" command

The general form of UNIX command is

commandname [options] filename-or-dirname-or-others

"Options" are optional, and you may omit it and use the "default options" ("default" means the values to use in case user does not supply any). Also notice that "options" begin with "-", e.g. "-i", "-rf". (There are a few commands that we may omit "-", e.g.

tar czvf tarfilename file1 file2 ... dir1 dir2 ...

is the same as

tar -c -z -v -f tarfilename file1 file2 ... dir1 dir2 ...

We shall discuss this command "tar" (=Tape Archive) later.

The default binary file from gcc is "a.out". We may change it with "-o binaryfilename" option.
e.g. we wish the binary file name from "psin.c" to be "sintable", and not "a.out", then
gcc -Wall -o sintable psin.c -lm

and to execute the program, type

sintable

Suppose we are to write a database program. The main program is in file "dbmain.c", and it needs five subroutines stored separately in files "add.c", "delete.c", "change.c", "create.c", "report.c".

The final binary file should have name, "dbmain".

For large programs, we should form "good programming practice" of writing each subroutine separately, and test them individually, before linking them into the main program.

Exercise :What files will be produced by the following commands,

gcc -Wall -c add.c
gcc -Wall -c delete.c
gcc -Wall -c change.c
gcc -Wall -c create.c
gcc -Wall -c report.c
gcc -Wall -c dbmain.c

Ans : add.o, delete.o, change.o, create.o report.o dbmain.o

Exercise : How to link them all into one program. Suppose we have to use library "libreport.a", and we wish the final binary file to be named "dbmain"?

Ans :

  gcc -Wall -o dbmain dbmain.o add.o delete.o change.o  create.o report.o -lreport

Exercise : How to check that the above command has been successfully run? and how to run the program, should there be no error?

Ans : To check the result of the last command, type "echo $?". If it shows "0", that means "o.k." Any value other than "0" signals error.
To run the program, just type "dbmain"

Exercise :Suppose after several days, we make some modification to the subroutines "report.c" and "change.c", what should we re-compile?

Ans :

       gcc -Wall -c report.c
       gcc -Wall -c change.c
       gcc -Wall -o dbmain dbmain.o add.o delete.o change.o create.o report.o -lreport

It can be seen that for each change we make, we have to re-type many commands (also, we may make mistakes in re-typing these commands. Or worse, we may forget the commands, or the filenames, or the subroutines, after some period of time). There is a UNIX command (or utility) to automate all these processes, called "make". Firstly, we have to use "emacs" to key in the following file, and use "makefile" for its filename.

 dbmain :  dbmain.o add.o delete.o change.o create.o report.o 
     gcc -Wall -o dbmain dbmain.o add.o delete.o change.o create.o report.o -lreport

 add.o : add.c
     gcc -Wall -c add.c

 delete.o : delete.c
     gcc -Wall -c delete.c

 change.o : change.c
     gcc -Wall -c change.c

 create.o : create.c
     gcc -Wall -c create.c

 report.o : report.c
     gcc -Wall -c report.c

 dbmain.o : dbmain.c  
     gcc -Wall -c dbmain.c

Notice that there is "indentation" before "gcc". You must press "Tab" to create this indentation, and NOT pressing spacebar several times. The utility program will fail if you do this.

The Utility "make"

make

When you just type in the command "make", the utility will search the file "makefile" (it will search only this file, hence you must use this file name.) and perform functions as shown

Notice that there many be many commands after the "target : dependencies" e.g.

         target1 : dep1 dep2 dep3 ....
                 command1
                 command2
                 command3
                      ....

         target2 : dep4 dep5 dep6 ....
                 command4
                 command5 
                       ....

          ...........
        

Sometimes, we wish to check what commands "make" will execute, without actually executing the commands, (this is useful in debugging the "makefile"), we may use
make -n
i.e. we use an "-n" option.
"make" will list all commands that it will execute, but without actually executing them.

Also, if the subroutines are too many to be put in one line in the "makefile", we should write, e.g.

          gcc -Wall -o dbmain  dbmain.o sub1.o sub2.o sub3.o sub4.o \
          sub5.o sub6.o sub7.o sub8.o sub9.o sub10.o sub11.o \
          sub12.o sub13.o
i.e. we put a "backslash" before we press "Enter = carriage return" key.

Note that "target" may be a non-existent filename. In that case, it will check the dependencies, and finally execute the commands. e.g. your "makefile" may be

          dummy :
                gcc -Wall psin.c -lm

Here "dummy" does not exist as a file, hence "make" will always execute

gcc -Wall psin.c -lm
and produce the executable binary "a.out".

If you want the executable binary to have name "sintable", you should use
         sintable :  psin.c
               gcc -Wall -o sintable psin.c -lm
for the "makefile".

How to edit and compile a program all within "emacs"

Usually, we use "emacs" to input the program, then save and exit "emacs". Then we issue the command, e.g.

gcc -Wall psin.c -lm
to compile the program. If there is no error, we may test run it by typing
a.out
But usually, we have compilation errors, and we have to edit again. We will have to re-run "emacs".

(Note : there is another way without exiting "emacs", as follows.)

We open the file
(ctrl +x -> ctrl + f, then filename) then key in the program, and finally save the program with "ctrl + x -> ctrl + s". Next we press
ctrl + z

"ctrl + z" means suspend "emacs" and return to the command prompt, i.e. exit from "emacs" temporarily.

We may check to see if "emacs" has really be suspended ("suspended" means being put in the "background". User at "command prompt" is said to be in the "foreground") by issuing the command :

jobs
This will show all background jobs running.

"Ctrl + z" has another use. Sometimes we run a program, and the program takes a very long time to finish, and we become impatient. Then we may suspend the job "Ctrl + z", then enter the command

bg

[ backgroud] to cause the suspended job to continue running in the background, without our attention.

In the command prompt, we may "gcc -Wall psin.c -lm" to compile the program. To correct compilation errors, we type

fg
[foreground] to enter into "emacs" again.
"fg" means " bring up a background job to foreground.

Or, if there are many jobs running in the background, then we use "jobs" to see how many background jobs are running, (it will show the jobs, and the job number), and use a modified form of "fg command,

fg n%

where "n" is the job number shown in jobs command.

But it is inconvenient, and there is a quicker way - "to compile within emacs"

The preferred way : to edit and compile all within "emacs"

First, you will have to "emacs" a "makefile" in your directory, it may be simply

             dummy :
                       gcc -Wall psin.c -lm
Remember the indentation before "gcc" is made by pressing "Tab" key, and not pressing spacebar many times. And then save with file with "ctrl + x -> ctrl + s".

Additional "emacs" commands are needed.

Alt + x -> compile -> Enter
First press "Alt" and "x" together, then type in "compile" , then press "Enter". Now "emacs" will compile automatically according to the content of the "makefile". Usually there will be compilation errors.
Ctrl + x -> `
Note that ` is the key at the top left hand corner.
This tells "emacs" to put cursor at the line where compilation errors occur. Pressing ctrl + x -> ` again will send the cursor to the next error, and so on. We may edit the offending lines one by one.
Ctrl + x -> o
[other] You will notice that "emacs" will have opened two windows. The top window is the editing window, and the bottom window is the compilation window. Pressing ctrl + x -> o will toggle between windows. If you are in the upper window, you will jump to the lower window, and vice versa.
Ctrl + x -> 1
[one] Destroy the other window, and leave only one window. If you are in the upper window, the lower window will be destroyed. Or if you are in the lower window, the upper window will be destroyed.
Ctrl + x -> 2
[two] This will open another window. The content of both windows are the same. You may jump to the other window, and open another file there.
Ctrl + x -> ctrl + b
[buffer] This will open another window at the bottom, and inside this window, all the opened file buffers will be displayed.

Reason why there may be more than one buffer is :

Sometimes we wish to "copy" from one file, and "paste" to another. Hence inside "emacs", we will have to open more than one files. This is done by "ctrl + x -> ctrl + f".

You can jump from one file to another also with this "ctrl + x -> ctrl + f", just type in the filename of the file you want to jump to.

After a while, you may form the custom of openning many files at once, and you may forget the filenames!
"ctrl + x -> ctrl + b" will show all the files you have opened. You may jump to that window, put the cursor at the filename you want to jump to, and press "Enter".

How to select several lines like that we are accustomed to do in Window ?

First move cursor to the starting position, and press

Ctrl + spacebar
to signify "start of selection"

Then move cursor to the ending position, usually the line below the last line to be selected, and press

Alt + w
for "copy" or
Ctrl + w
for "cut".

Then move to the place where we want to "paste". It may be in the same file, or in another file (that file should have already been opened with "Ctrl + x -> Ctrl + f") and press

Ctrl + y
[yank] to yank back the selected lines. This is "paste".

Ctrl + y has other uses, e.g. We delete some lines somewhere (ctrl + k = kill = delete a line), and want to put the deleted lines at other places. Then move the cursor there, and press "Ctrl + y".

These may seem confusing at first. But you need only to know how to edit now. It is advisable that you find someone familiar with computer to show you, and you will find it is not difficult at all, though it will take some times to get used to it.


[Previous] [Home] [Next]