Вы находитесь на странице: 1из 27

Adama University, SOE, Department of Information Technologies

Working with Basic Linux Commands

version 1.0 Compiled by: Fisseha T. & Maereg Enq April 2011

Fisseha T. , Maereg Enq.

Linux Operating System lab Manual

Adama University, SOE, Department of Information Technologies

Preface
This material is re-organized to facilitate the teaching-learning of the course Operating System lab class in Adama University undergraduate program. This note starts from the second part of the Linux tutor. The first tutor is installation procedure that contains the requirements and steps that you face while installing Linux (like Debian).In this part you will learn how to work with some basic Linux commands, vi text editor and commands we use on it, shell scripting with examples and C fundamentals. The commands on this documentation are experimented on Debian though the design philosophy of Linux certify that commands work pretty the same way on other distribution.This documentation is for absolute beginners who would want to get an accelerated tutorial. This tutorial is presumed to get you up to speed of working with Linux commands. The original documentation is belongs to Mr Tadele T. who is now in Norway, studying complex digital library system in university of Oslo. He was my operating system and computer organization and architecture teacher. An INDEED GENUINE THANKS to HIM!!!

You are free to copy or distribute part or all of the documentation in whatever way or format as responsibility of the damage or trouble caused by this documentation fall by no means on my shoulder. However, I have tried all my best to make this documentation a usable more often than, not a cause for mayhem.

Fisseha T. , Maereg Enq.

Linux Operating System lab Manual

Adama University, SOE, Department of Information Technologies

WHAT IS LINUX?
Linux is a free operating system that was created by Linus Torvalds when he was a student at the University of Helsinki in 1991. When compared to different commercially available operating systems, Linuxs best assets are its price and its reliability. Most people know that its initial price is free. However, when people talk about Linuxs affordability, they are usually thinking of its total cost, which includes no (or low) licensing fees and the capability of using inexpensive hardware and compatible free add-on applications. Although commercial operating systems tend to encourage upgrading to later hardware, Linux doesnt (although faster hardware and larger disks are nice to have ). Another advantage of using Linux is that help is always available on the Internet. There is probably someone out there in a Linux newsgroup or mailing list willing to help you get around your problem. Because the source code is available, if you need something fixed you can even patch the code yourself. Linux is a comprehensive operating system with a number of features and capabilities. Its major features are: Multi-user, Time Sharing OS Multitasking OS Portability Modularity System security File Structure and Security I/O Redirection and Piping I/O independence Communication THE STRUCTURE OF LINUX SYSTEM The Linux OS may be functionally categorized into: _ The Kernel _ The Shell _ Utilities/Tools and Applications. User Applications and tools Kernel Hardware Shell

Fisseha T. , Maereg Enq.

Linux Operating System lab Manual

Adama University, SOE, Department of Information Technologies

Kernel
The Linux kernel is the heart of the operating system, providing the communication bridge between hardware and software. It is the master program which controls the computers resources, allocates them to users and to different tasks. The kernel directly controls the hardware. It controls functions like File Management and Security, Input/Output services, Memory Management, Process Scheduling and Management, System accounting, Interrupt and Error handling, and also Date and time services. Besides this, it also ensures an interaction without conflict between physical resources like the processor, memory and the peripherals as well as the software processes and files. The Shell The shell is one layer above the kernel. It acts as a command interpreter for the commands input by the user. The shell takes the user commands as input, processes them into suitable system calls to interact with the kernel which in turn interacts with the hardware to perform the task. The kernel does the actual fetching and returning of data at the request of the shell. The shell does not interact directly with the hardware. The shell has some basic commands which are directly understandable by it. Additionally it contains a programming language which enables the users to write shell scripts on their own. The Linux Shell performs the following functions: It acts as a command interpreter for the basic commands (both internal and external) It expands the various meta-characters used in file operations. (Like *,? [], {}, etc) It is responsible for executing the shell scripts which use the programming language of the shell. The shell has a programming language with in-built logical looping and testing constructs, which enable the users to create their own programs. The shell is responsible for setting up the environment for the user. The environment includes pathname (the directory paths to be searched for an executable program), various directory names (HOME directory, which is the default login directory, MAIL directory mail messages etc.)

1.

Logging into the system

There are two ways to log into the system after installation. In may Debian 6.0, I can log in as a normal user (the user I have created during installation) or as the built in root account. If you want to log-in as root, use the character based log-in. Press <control+alt+F1> together to get the text mode log-in. Otherwise you can loin as a normal user on the x-window and su to get the root privilege. To get in to the x-window press <control+alt+F7>. Though the principles applies true to both mechanisms of logging, my discussion focuses on the xwindow as people coming on the way down like to float first. Now I expect you are logged in to your system and your are on the Desktop. Navigate the Desktop using your mouse and see what you can do with it. Play nice and easy games. Bring document files or music files or movie files.... using your external memory disk (CD/DVD/flash)... mount it and then do what you want to do. Easy... just like other operating environments you are familiar with. Let us look at the other workarounds of the operating environment. If you log-in to the text based, you will have your default shell; but in the GUI, you need to open your shell (GNOME terminal) how? 4
Fisseha T. , Maereg Enq. Linux Operating System lab Manual

Adama University, SOE, Department of Information Technologies Use your mouse and click on Applications----->accessories--->terminal and that will give you the terminal (bash in this case) screen. That is what we refer as the shell. Let's venture together then. commands are typed on it and outputs can also be directed or displayed on it or not... lets get started.

What is COMMANDS
The shell is a command interpreter. It takes commands typed on the command line as arguments. Modifying flags (usually the sign) as well as major arguments such as filenames. Arguments are usually separated by a white space which is just spaces or tab characters. The command name is argument zero. Predefined shell variables The shell also has some predefined variables. Some of these can be modified. HOME Users home directory PATH The directories that the system searches to find commands PS1 $ the system prompt LOGNAME Displays the users login name In computers, a command is a specific order from a user to the computer's operating system or to an application to perform a service, such as "Show me all my files" or "Run this program for me." Commands may be invoked as simple commands. In these examples, the $ that starts each line is a shell prompt and not meant to be typed.
$ ls

Or they may be invoked as complex commands.


$ ls -l /bin

Here "-l /bin" are a pair of arguments (separated from each other and the command by white-space) and "-l" is specifically an option, since it modifies the behavior of ls (it produces a long listing), while "/bin" simply specifies a target for ls to act on. They may also be invoked in multiples where the semi-colon is a command separator.
$ cd /bin; ls

Another way to invoke multiple commands is conditionally, where (in bash) "&&" means to execute the second command only if the first returns with an exit code of 0 (i.e., it succeeds).
$ cd /bin && ls

With the semicolon command separator, had the change of directory failed, ls would still have been invoked and simply listed the contents of the current directory. With the conditional operator, ls would not be invoked if cd had failed. Similarly, "||" means to execute the second command only if the first returns a non-zero exit code (i.e., it fails).
$ cd /bing 2>/dev/null || echo 'I kinna do it, Cap'\''n!'

This will change to the directory named "bing" if it in fact exists and the command will exit. Since it probably doesn't, being a typo, the second command will execute and print a somewhat more entertaining error message than is usual.

Fisseha T. , Maereg Enq.

Linux Operating System lab Manual

Adama University, SOE, Department of Information Technologies You can use a pipeline (symbolized by "|") to make the output of one command serve as the input to another command. This idea can be used to create a combination of commands to accomplish something no single command can do. Enter this command: $ echo "cherry apple peach" cherry apple peach Okay, let's say we want to sort these words alphabetically. There is a command "sort", but it sorts entire lines, not words, so we need to break this single line into individual lines, one line per word. Step one: pipe the output of "echo" into a translation (tr) command that will replace spaces with linefeeds (represented by "\n"): $ echo "cherry apple peach" | tr " " "\n" cherry apple peach Success: each word appears on a separate line. Now we are ready to sort. Step two: add the sort command: $ echo "cherry apple peach" | tr " " "\n" | sort apple cherry peach Let's try reversing the order of the sort: $ echo "cherry apple peach" | tr " " "\n" | sort -r peach cherry apple Remember: A pipeline ("|") takes the output of one command and makes it the input to another command.

2.

basic commands

$ echo $SHELL This command will print for your the shell you are working with. In my case it gave me /bin/bash $ pwd This command prints the name of the current working directory. In my case it gave me /home/fisseha $ whoami This command displays the current user name. in my case it gave me fisseha. $ file file-name Displays the type of file $ apropos ftp Displays the commands related to ftp. If you do not know the command but would like to see commands relevant to a topic. The same output can be obtained by $ man -k ftp. $ whatis command-name 6
Fisseha T. , Maereg Enq. Linux Operating System lab Manual

Adama University, SOE, Department of Information Technologies Displays a one line description about the command-name. like $ whatis ls $ man command will show you the manual page of command. Example $ man ls $ ls Lists the contents of a directory ( the most frequently used command).see the manual for detail options like ls -a , ls -d or ls -l etc. $ ls l - Gives a long listing $ ls a - Displays all files including hidden files $ ls al - Displays all files including hidden files in a long listing $ mkdir myfiles makes a directory called myfiles under the present working directory. $ rmdir myfiles removes a directory called myfiles from the present working directory. The directory must be empty otherwise use $ rmdir -p or -r myfiles/dir2 if there exist other directory inside the directory. $ cd myfiles change your present working directory in to myfiles. A default cd without any argument will take you to your home directory. And cd .. will take you parent directory of the current directory(one step back) where as cd will take you back to the previous working directory. See the man page for detail. $ touch myfile creates an empty file called myfile on the present directory. eg. touch test.doc $ cp myfile myfiles copies the file myfile to the directory myfiles. To copy one directory to another directory use recursive (-r) option along with the cp command. like $ cp -r me fish or $ cp me -r fish $ rm myfile removes the file myfile from the current directory. $ mv myfile mynewfile renames myfile with a new name called mynewfile. it also rename the directory. $ ps It is another useful command displaying running process. The longer you use Linux, you will come time and again to use ps with all its other options. See the man if you are impatient to wait. $ ps -f, gives user-id, the pid for the parent of each process, the amount of CPU resources used by the process, STIME gives the time when the process started. $ ps -e, displays information about all process started. $ gzip myfile compresses myfile and creates myfile.gz $ gunzip myfile.gz recreates myfile back again from myfile.gz. $bzip2 myfile this also creates myfile.bz2 out of myfile. the difference is between gzip and bzip2 lies in the compression algorithms they use. $ bunzip2 myfile.bz2 recreates myfile back out of myfile.bz2 7
Fisseha T. , Maereg Enq. Linux Operating System lab Manual

Adama University, SOE, Department of Information Technologies $ tar -cvvf myfile.tar myfile/ creates myfile.tar out of the contents of files found in the directory myfile. This tools are used to make archives. $ tar -xvvf myfile.tar Extracts myfile.tar into a folder containing the files of myfile.tar $ tar cvvzf myfile.tar.gz myfile/ Creates an archive file called myfile.tar.gz out of the files found inside myfile directory. Fine then remove myfile using rm r myfile and extract the contents back into myfile using $ tar xvvzf myfile.tar.gz $ date Date is a general purpose command to display the current date and time. This can be specified in a number of formats: $ date +[options] %m - displays the month of the year %d - displays day of the month %y - displays last two digits of the year %H - displays hour of the day %M - displays minute of the day %S - displays second of the day %r - displays time as AM / PM example : $ date +%d $ cal cal is a command used to display the current month as standard output. We can specify the month and the year also, like $ cal [month] [year].

Variables in Shell
To process our data/information, data must be kept in computers RAM memory. RAM memory is divided into small locations, and each location had unique number called memory location/address, which is used to hold our data. Programmer can give a unique name to this memory location/address called memory variable or variable (Its a named storage location that may take different values, but only one at a time). In Linux (Shell), there are two types of variable: (1) System variables - Created and maintained by Linux itself. This type of variable defined in CAPITAL LETTERS. (2) User defined variables (UDV) - Created and maintained by user. This type of variable defined in lower letters. some of the important System variables are:

Fisseha T. , Maereg Enq.

Linux Operating System lab Manual

Adama University, SOE, Department of Information Technologies System Variable BASH=/bin/bash BASH_VERSION=1.14.7(1) COLUMNS=80 HOME=/home/vivek LINES=25 LOGNAME=students OSTYPE=Linux PATH=/usr/bin:/sbin:/bin:/usr/sbin PS1=[\u@\h \W]\$ PWD=/home/students/Common SHELL=/bin/bash USERNAME=vivek Our shell name Our shell version name No. of columns for our screen Our home directory No. of columns for our screen students Our logging name Our Os type Our path settings Our prompt settings Our current working directory Our shell name User name who is currently login to this PC Meaning

NOTE that Some of the above settings can be different in your PC/Linux environment. You can print any of the above variables contains as follows: $ echo $USERNAME $ echo $HOME

How to define User defined variables (UDV)


To define UDV use following syntax Syntax: variable name=value 'value' is assigned to given 'variable name' and Value must be on right side = sign. Example: $ no=10# this is ok $ 10=no# Error, NOT Ok, Value must be on right side of = sign. To define variable called 'vech' having value Bus $ vech=Bus To define variable called n having value 10 $ n=10 9
Fisseha T. , Maereg Enq. Linux Operating System lab Manual

Adama University, SOE, Department of Information Technologies

Rules for Naming variable name (Both UDV and System Variable)
(1) Variable name must begin with Alphanumeric character or underscore character (_), followed by one or more Alphanumeric character. For e.g. Valid shell variable are as follows HOME SYSTEM_VERSION vech no (2) Don't put spaces on either side of the equal sign when assigning value to variable. For e.g. In following variable declaration there will be no error $ no=10 But there will be problem for any of the following variable declaration: $ no =10 $ no= 10 $ no = 10 (3) Variables are case-sensitive, just like filename in Linux. For e.g. $ no=10 $ No=11 $ NO=20 $ nO=2 Above all are different variable name, so to print value 20 we have to use $ echo $NO and not any of the following $ echo $no # will print 10 but not 20 $ echo $No# will print 11 but not 20 $ echo $nO# will print 2 but not 20 (4) You can define NULL variable as follows (NULL variable is variable which has no value at the time of definition) For e.g. $ vech= $ vech="" Try to print it's value by issuing following command $ echo $vech Nothing will be shown because variable has no value i.e. NULL variable. (5) Do not use ?,* etc, to name your variable names.

How to print or access value of UDV (User defined variables)


To print or access UDV use following syntax Syntax: $variablename Define variable vech and n as follows: $ vech=Bus $ n=10 To print contains of variable 'vech' type $ echo $vech It will print 'Bus',To print contains of variable 'n' type command as follows 10
Fisseha T. , Maereg Enq. Linux Operating System lab Manual

Adama University, SOE, Department of Information Technologies $ echo $n Caution: Do not try $ echo vech, as it will print vech instead its value 'Bus' and $ echo n, as it will print n instead its value '10', You must use $ followed by variable name.

Shell Arithmetic
Use to perform arithmetic operations. Syntax: expr op1 math-operator op2 Examples: $ expr 1 + 3 $ expr 2 - 1 $ expr 10 / 2 $ expr 20 % 3 $ expr 10 \* 3 $ echo `expr 6 + 3` Note: expr 20 %3 - Remainder read as 20 mod 3 and remainder is 2. expr 10 \* 3 - Multiplication use \* and not * since its wild card. For the last statement not the following points (1) First, before expr keyword we used ` (back quote) sign not the (single quote i.e. ') sign. Back quote is generally found on the key under tilde (~) on PC keyboard OR to the above of TAB key. (2) Second, expr is also end with ` i.e. back quote. (3) Here expr 6 + 3 is evaluated to 9, then echo command prints 9 as sum (4) Here if you use double quote or single quote, it will NOT work For e.g. $ echo "expr 6 + 3" # It will print expr 6 + 3 $ echo 'expr 6 + 3' # It will print expr 6 + 3 $ echo `expr 6 + 3` # It will print 9

VI editor
VI editor has two modes: command and insert mode. The command mode is the default mode when vi startes. The insert mode puts anything typed on the keyboard into the current file. VI starts out in command mode. There are several commands that put the VI editor into insert mode. The most commonly used commands to get into insert mode are a and i.

Common vi editor command list


For this Purpose 11
Fisseha T. , Maereg Enq.

Use this vi Command Syntax


Linux Operating System lab Manual

Adama University, SOE, Department of Information Technologies To insert new text To save file To save file with file name (save as) To quit the vi editor To quit without saving To save and quit vi editor To search for specified word in forward direction To continue with search To search for specified word in backward direction To copy the line where cursor is located To paste the text just deleted or copied at the cursor To delete entire line where cursor is located To delete word from cursor position To Find all occurrence of given word and Replace then globally without confirmation To Find all occurrence of given word and Replace then globally with confirmation To run shell command like ls, cp or date etc within vi 12
Fisseha T. , Maereg Enq.

esc + i ( You have to press 'escape' key then 'i') esc + : + w (Press 'escape' key then 'colon' and finally 'w') esc + : + w "filename" esc + : + q esc + : + q! esc + : + wq esc + /word (Press 'escape' key, type /word-to-find, for e.g. to find word 'shri', type as /shri) n esc + ?word (Press 'escape' key, type word-to-find) esc + yy esc + p esc + dd esc + dw esc + :$s/word-to-find/word-to-replace/g For. e.g. :$s/mumbai/pune/g Here word "mumbai" is replace with "pune"

esc + :$s/word-to-find/word-to-replace/cg

esc + :!shell-command For e.g. :!pwd

Linux Operating System lab Manual

Adama University, SOE, Department of Information Technologies

To delete a character navigate the text using h(left), l(right), k(up) and j(down). Typing 3j will take you to the third line below the cursor. Then after typing x will delete one character at a time, u will undo changes and pressing ctrl+r will redo changes. If you want to add the contents of another file to your opened file simply type :r filename_to_added and that will add the contents of the file down the cursor.

Shell script
A shell script is a plain-text file that contains shell commands. It can be executed by typing its name into a shell, or by placing its name in another shell script. To be executable, a shell script file must meet some conditions: The file must have a special first line that names an appropriate command processor. the following will work in most cases: #!/bin/bash The file must be made executable by changing its permission bits. An example: $ chmod +x (shell script filename) A shell script file may optionally have an identifying suffix, like ".sh". This only helps the user remember which files are which. The command processor responsible for executing the file uses the executable bit, plus the file's first line, to decide how to handle a shell script file. One normally executes a shell script this way: $ ./scriptname.sh This will get you past the details of writing and launching a simple script. 1. Choose a text editor you want to use. It can be a command-line editor like gedit or vi, or an X Windows editor if you have this option. 2. Run your choice of editor and type the following lines: #!/bin/bash echo "Hello, world." 3. Save the file in the current working directory as "myscript.sh". 4. Move from the text editor to a command shell. 5. From the command shell, type this: $ chmod +x myscript.sh 6. To execute the script, type this: 7. $ ./myscript.sh Hello, world.

Tests and Branching


Bash shell scripts can perform, and act on, various kinds of tests. Here is an example of a test and branch: 13
Fisseha T. , Maereg Enq. Linux Operating System lab Manual

Adama University, SOE, Department of Information Technologies if [ -e . ] then echo "Yes." else echo "No." fi

Run the test script: $ ./myscript.sh

Yes. We created a test (the part of the script between "[" and "]") which tested whether a particular element existed ("-e"). Because the symbol "." in this context means the current directory, the test succeeded. Try replacing the "." with something that is not present in the current directory, example "abc". See how the outcome changes. It is important to realize that "[" is an alias for the command "test". The script could have been written as:

if test -e . then echo "Yes." else echo "No." fi when a test is conducted or a command returns a result value, the numerical value for "true" is 0, and "false" is 1. Here is a way to get the result of the most recent logical test (and to show the weird reversal described above): $ test -e . $ echo $? 0 $ test -e xyz $ echo $? 1

Loops and Repetition


Here are some examples of loop operators: for fn in *; do echo "$fn" done In this example, the "*" is expanded by the shell to a list of all the files in the current directory, then 14
Fisseha T. , Maereg Enq. Linux Operating System lab Manual

Adama University, SOE, Department of Information Technologies each filename is applied to the loop control area. You can solve such a problem this way (there are other solutions): ls -1 | while read fn; do echo "$fn" done on the above example we can leave the option -1, its advantage is to make one name per line.

Using Numbers in Scripts


Numbers can easily be accommodated in scripts. Example: n=1 while [ $n -le 6 ]; do echo $n let n++ done $ ./myscript.sh 1 2 3 4 5 6 Here is a somewhat more complex example: y=1 while [ $y -le 12 ]; do x=1 while [ $x -le 12 ]; do printf "% 4d" $(( $x * $y )) let x++ done echo "" let y++ done $ ./myscript.sh 1 2 3 4 5 6 15 2 3 4 5 6 7 8 9 10 11 12 4 6 8 10 12 14 16 18 20 22 24 6 9 12 15 18 21 24 27 30 33 36 8 12 16 20 24 28 32 36 40 44 48 10 15 20 25 30 35 40 45 50 55 60 12 18 24 30 36 42 48 54 60 66 72
Fisseha T. , Maereg Enq. Linux Operating System lab Manual

Adama University, SOE, Department of Information Technologies 7 14 21 28 35 42 49 56 63 70 77 84 8 16 24 32 40 48 56 64 72 80 88 96 9 18 27 36 45 54 63 72 81 90 99 108 10 20 30 40 50 60 70 80 90 100 110 120 11 22 33 44 55 66 77 88 99 110 121 132

12 24 36 48 60 72 84 96 108 120 132 144 Exercise1. Write shell script that display the following output. 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 1 2 3 4 5 6 7 1 2 3 4 5 6 7 8

Coping with user input


Here is an example that relies on user input to decide what to do. It exploits a shell feature as an easy way to create a menu of choices: PS3="Choose (1-5):" echo "Choose from the list below." select name in red green blue yellow magenta do break done echo "You chose $name." When run, it looks like this: $ ./myscript.sh

16

Fisseha T. , Maereg Enq.

Linux Operating System lab Manual

Adama University, SOE, Department of Information Technologies Choose from the list below. 1) red 2) green 3) blue 4) yellow 5) magenta Choose (1-5):4 You chose yellow. As written, this menu code won't catch some kinds of errors (like a number that is out of range). In any application where the user choice must fall into defined bounds, be sure to perform a test on the result before using it. Example: if [ "$name" = "" ]; then echo "Error in entry." exit 1

fi

Creating and using arrays


Shell arrays are relatively easy to construct. Example: array=(red green blue yellow magenta) len=${#array[*]} echo "The array has $len members. They are:" i=0 while [ $i -lt $len ]; do echo "$i: ${array[$i]}" let i++ done Run this example: $ ./myscript.sh The array has 5 members. They are: 0: red 1: green 2: blue 3: yellow 4: magenta Now, before you decide this is a silly, rather useless example, replace one line of the script and run it again:

17

Fisseha T. , Maereg Enq.

Linux Operating System lab Manual

Adama University, SOE, Department of Information Technologies

array=(`ls`) 3. Shell Wildcards

Wildcards are used to facilitate processing multiple requests without the need to type them all. * (matches a group of 0 or more characters) but doesnt match a filename started with (.) ? (Matches exactly one character.) [...] matches exactly one character with any character enclosed in brackets. [a-z] matches exactly one character between a and z [^...] matches exactly one character other than the one enclosed in brackets. You can use wildcards with any command that accepts file names as arguments.

Examples
$ mkdir temp; cd temp; touch 1.txt 2.txt 3.c 4.n $ echo *.txt 1.txt 2.txt $ echo * 1.txt 2.txt 3.c 4.n $ echo *.[hc] 3.c $ echo [^1-3]* 4.n $ cd ..; rm -rf temp // this will remove directory temp and files it contain. Let's have a few extra examples. Probably the * character is already familiar to you, because it's widely used in many other places, too, not just in Linux. For example, the following removes every file from the current directory: $ rm * The following command moves all the HTML files, that have the word "linux" in their names, from the working directory into a directory named dir1: $ mv *linux*.html dir1 See, I told you that moving multiple files can be just as simple as moving only one file! The following displays all files that begin with d and end with .txt: $ less d*.txt The following command removes all files whose names begin with junk., followed by exactly three characters: $ rm junk.???

18

Fisseha T. , Maereg Enq.

Linux Operating System lab Manual

Adama University, SOE, Department of Information Technologies With this command you list all files or directories whose names begin with hda, followed by exactly one numeral: This command copies all files, that begin with an uppercase letter, to directory dir2: $ cp [A-Z]* dir2 This deletes all files that don't end with c, e, h or g: $ rm *[!cehg]

4.

Command aliasing

The alias command can be useful if you want to create a 'shortcut' to a command that you use most frequently. The format is alias name='command' Example $ alias list='ls -la' This will create an alias called list, which will use the ls command to print a long-style listing of all files in the current directory (the -l gives a long-style list, and the -a shows all files - including hidden files). $ alias home='cd /home/fisseha/downloads' This will create an alias called home which will put you in the /home/fisseha/downloads directory whenever you type home at the command prompt. You can alias any command you want, and include options for the command. The unalias command is used to remove an alias. The format is $ unalias name $ unalias home //This will remove the alias called home.

5.

Text processing
cat filename concatinate the file and print on the terminal. head output the first part of the file tail output the last part of the file sort sorts a line of text files uniq removes duplicate lines from a sorted file tr translates or deletes characters diff and cmp compares files, like cmp file1 file2

cat list-1 list-2 list-3 | sort | uniq > final.list $ Concatenates the list files, $ sorts them, $ removes duplicate lines, $ and finally writes the result to an output file.

19

Fisseha T. , Maereg Enq.

Linux Operating System lab Manual

Adama University, SOE, Department of Information Technologies


The useful -c option prefixes each line of the input file with its number of occurrences. $ cat testfile This line occurs only once. This line occurs twice. This line occurs twice. This line occurs three times. This line occurs three times. This line occurs three times. $ uniq -c testfile 1 This line occurs only once. 2 This line occurs twice. 3 This line occurs three times. $ sort testfile | uniq -c | sort -nr 3 This line occurs three times. 2 This line occurs twice. 1 This line occurs only once.

6.

Files and Directories

File and directory access permissions are defined separately for the following three categories of affected users: the user who owns the file (u), other use in the group which the file belongs to (g), and all other users (o). For a file, each corresponding permission allows: read (r): to examine contents of the files, write (w): to modify the file, and execute (x): to run the file as a command. For a directory, each corresponding permission allows: read (r): to list contents of the directory, write (w): to add or remove files in the directory, and execute (x): to access file in the directory. Here, execute permission on the directory means not only to allow reading of files in the directory but also viewing their attributes, such as the size and the modification time. To display permission information(and more) for files and directories, ls -l command is used. Type "ls -l" and a listing like the following is displayed: Total 10 drwxrwxrw fisseh 4 x a fisseh -rw-rw-rw- 1 a fisseh -rw-rw-rw- 1 a 20 team 1 team 1 team 1 Dec 12 18:02 187 Aug 23 3 08:34 123 Sep 12 4 11:13 122 Project s test datafil e
Linux Operating System lab Manual

Fisseha T. , Maereg Enq.

Adama University, SOE, Department of Information Technologies Which means the following: Type and Permission field | drwxrwxrwx # of Lin ks | 4 Files' s Own er | fisse ha File' Size Date of last s in Grou modificatio Bytes p n | | | team Dec 12 122 1 18:02 Filenam e

| Projects

What do the letters mean in front of the files/directories mean? r indicates that it is readable(someone can view the files contents) w indicates that it is writable(someone can edit the files contents) x indicates that it is executable(someone can run the file, if executable) - indicates that no permission to manipulate has been assigned -the type of file(first character) - : normal file d :directory l :symlink c :character device node b :block devise node p : named pipe s : socket -the files access permission ( the next nine characters,consisting of three characters each for user, group, and other in the order) -the number of hard links to the file -the name of the user who owns the file -the name the group which the file belongs to -the size of the file in characters (bytes) -the date and time of the file (mtime) -the name of the file To change the owner of the file, chown is used from the root account. To change the group of the file, chgrp is used from the files owner or the root. To change file and directory access permission, chmod is used from the file's owner or root. Basic syntax to manipulate foo file is: # chmod newowner foo # chgrp newgroup foo # chmod [ugo][+/-][rwx][,...] foo / here + is to add permission, - is to remove permission. File access permissions can be changed in two ways. Symbolic mode or Absolute mode. The Symbolic mode indicates particular permissions to be set. The symbolic mode consists of three parts, who is affected, the operator indicating action taken, and the permission. $ chmod [ugo] [+/-] [rwx] [filename] Absolute mode indicates the exact settings for all permissions. In the absolute mode octal numbers 21
Fisseha T. , Maereg Enq. Linux Operating System lab Manual

Adama University, SOE, Department of Information Technologies are used to represent the three kinds of access permissions. The octal values are: 4 read permission 2 write permission 1 execute permission

user permissions Octal values Octal values sum Octal value =777 user permissions Octal values Octal values sum Octal value = 764 user permissions Octal values Octal values sum Octal value = 752 22

Owner rwx 421 7

Group rwx 421 7

Others rwx 421 7

Owner rwx 421 7

Group rw420 6

Others r-400 4

Owner rwx 421 7

Group r-x 401 5

Others -w020 2

Fisseha T. , Maereg Enq.

Linux Operating System lab Manual

Adama University, SOE, Department of Information Technologies A combination of the values is used to specify access permissions. more on permission : chmod u+x myfile chmod +x myfile chmod ugo+x myfile chmod 400 myfile Gives the user execute permission on myfile. Gives everyone execute permission on myfile. Same as the above command, but specifically specifies user, group and other. Gives the user read permission, and removes all other permission. These permissions are specified in octal, the first char is for the user, second for the group and the third is for other. The high bit (4) is for read access, the middle bit (2) os for write access, and the low bit (1) is for execute access. Gives user full access, group read and write access, and other read access. Gives user full access, group read and execute permission, and other, execute permission. Set the setuid bit. Remove read and execute permissions for the group and other.

chmod 764 myfile chmod 751 myfile chmod +s myfile chmod go=rx myfile

chown mark test1Changes the owner of the file test1 to the user Mark. chgrp mark test1Changes the file test1 to belong to the group "mark".

More on chmod :
The chmod command allows you to alter access rights to files and directories. All files and directories have security permissions that grant the user particular groups or all other users access. When listing your files, the first character lets you know whether youre looking at a file or a directory. Its not part of the security settings. The next three characters indicate Your access restrictions. The next three indicate your group's permissions, and finally other users' permissions. Use chmod followed by the permission you are changing. In very simple form this would be: chmod 755 filename The example above will grant you full rights, group rights to execute and read, and all others access to execute the file. # 7 6 5 4 3 23 Permission full read and write read and execute read only write and execute
Linux Operating System lab Manual

Fisseha T. , Maereg Enq.

Adama University, SOE, Department of Information Technologies 2 write only 1 execute only 0 none Still confused? Use the table above to define the settings for the three "users." In the command, the first number refers to your permissions, the second refers to group, and the third refers to general users. Typing the command: chmod 751 filename gives you full access, the group read and execute, and all others execute only permission.

7.

Timestamps

There are three types of timestamps for a GNU/Linux file : mtime :the modification time (ls -l), ctime : the status change time (ls -lc), and atime : the last access time (ls -lu). Note that ctime is not file creation time. -overwriting a file will change all of mtime,ctime, and atime of the the file. -Changing permission or owner of a file will change ctime and atime of the file. -reading of a file will change atime of the file. Use touch command to change timestamps of existing files.

LINUX PROGRAMMING BASICS C fundamentals


The following is a sample C program. /* This is a comment and hello.c is name of the program*/ #include <stdio.h> /* stdio.h is a standard header file */ int main() { /* this function is always called first */ printf("Hello, world!\n"); /*\n is the new line character */ return 0; /* main() should return 0 up on normal finish */ } Compile the program using: $ gcc -Wall hello.c If you haven't explicitly stated the name of the binary file, gcc will create a default executable file named a.out. The -Wall command is to request gcc to print warnings about our program and execute your program using: 24
Fisseha T. , Maereg Enq. Linux Operating System lab Manual

Adama University, SOE, Department of Information Technologies $ ./a.out Hello, world! $ If you would like to give your own name to your program use -o command line option along with your preferred name like: $ gcc -Wall hello.c -o preferred_name 1. Create Source Code

To start, create the following sample source code file and save it as hello.c. The following sections show you how to compile this file to form an executable and how to run it. #include<stdio.h> int a, c; void foo (int b) { c = a + b; printf("%d + %d = %d\n", a, b, c); } int main () { int b; a = 3; b = 4; printf ("Hello, world!\n"); foo (b); return 0; } 2. Compile, Assemble, and Link from Source Code to compile the code, use the following command: $ gcc o hello hello.c The o specifies the name of the executable to be produced. 3. Run the Executable To run the program, use the following example: $ ./hello The program generates Hello word! 3+4=7 The following program swamp the value of variable x to variable y and vice verse. 25
Fisseha T. , Maereg Enq. Linux Operating System lab Manual

Adama University, SOE, Department of Information Technologies #include<stdio.h> main( ) { double temp; double x = 15.7; double y = 3; printf("Before changing....\n"); printf("%%5.2f %5.2f\n", x, y); if( x > y) { temp = x; x = y; y = temp; printf("After changing ....\n"); printf("%5.2f %5.2f\n", x, y); } } printf format strings %d signed int %u unsigned int %x hexadecimal unsigned int %c character %f double and float %s string %% to print a % /* Program to print all the format of values */ #include<stdio.h> int main( ) { int number = 10; char s='A'; char str[20]=("Nazareth College\n"); printf("Decimal Format : %d\n",number); printf("Scientific Format : %e\n",number); printf("Float Format : %f\n",number); printf("Octal Format : %d\n",number); printf("Hex Format : %x\n",number); printf("Character Format : %c\n",s); 26
Fisseha T. , Maereg Enq. Linux Operating System lab Manual

Adama University, SOE, Department of Information Technologies printf("String Format: %s\n",str); return 0; } Exercises 1. Write a program which defines an integer, a float, a character and a string, then displays them on screen with some calculation. 2. Write a program which computes and displays fib(15): f ib(0) = 0, f ib(1) = 1 If n > 1 then f ib(n) = f ib(n 1) + f ib(n 2)

27

Fisseha T. , Maereg Enq.

Linux Operating System lab Manual

Вам также может понравиться