Workshop On LINUX Shell Commands, Shell Script and System Calls

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 26

Workshop on LINUX

Shell Commands, Shell Script and System Calls

Listing files and directories


1) ls (list)

ls stands for List and this command gets system to display the list of files in the directory
you are referring to. The default directory is your current directory.

To find out what is in your current directory, type

$ ls

The ls command lists the all files and subdirectories of your current working directory.

Listing Options

Option Action

ls -a Lists all directories including . Entries

ls -i Lists files with I node numbers

ls -l Lists in long form

ls -r Lists files in reverse order

ls -t Lists files sorted by last modified time

ls -u Lists files sorted by last access time

ls -lt Lists files in long form sorted by last modified time

ls -R recursive list of all files in all subdirectories

We can also use wildcard characters (*,?) with this command.

E.g. $ ls ?
Introductory Linux Workshop 1
SCET, Surat
20th March 2009
Display all files/ directories having single character name.

$ ls *.c

Display all files with extension .c

$ ls game*

Display all files with names starts with game keyword like games1, games2,
games11, gameskid etc.

2) cat

This command is useful to create file as well as to display content of files. It is also
useful to append new data into files.

$ cat > abc.txt

This command create file abc.txt. Here > sign is know as redirection operator. When
use this command, system will create blank abc.txt file and gives you space to write
content. At the end of file press ctrl + Z to save and exit from file. If you try same
command again, system will remove all content from file and open blank file with same
name.

$ cat abc.txt

This command displays the content of file(s). You can see contents of more than one file
using same command.

$ cat abc.txt xyz.txt

This command displays the content of abc.txt followed by the content of xyz.txt.

$ cat >> abc.txt

This command is used to append new data in the file abc.txt.

3) cp

Copy the content of an existing file into another file in the same directory or in the other
directory.

$ cp birds birds1

This command copies file birds into birds1.

Introductory Linux Workshop 2


SCET, Surat
20th March 2009
$ cp birds /home/student/

Copy content the file birds into another directory having name student which is
currently in home directory. The name of the file in target directory remains same. To
copy a file into another directory full path name of the target file is needed.

4) rm

Delete or Remove file(s).

$ rm abc.txt

This command will remove file having name abc.txt.

$ rm abc.txt xyz.txt

This command will remove two files abc.txt and xyz.txt.

5) mv

Rename file or move file.

$ mv birds birds1

This command will rename file birds with birds1. Here, birds1 is available in same
directory.

$ mv birds ./new/birds1

This command will move file birds to new directory under current working directory
with the new name birds1.

6) wc

Perform Word count.

$ wc file1

This command will display number of lines, number of words and number of
characters in the files and name of that file.

Option Action

wc -l Display only total number of lines in a file with file name

Introductory Linux Workshop 3


SCET, Surat
20th March 2009
wc -w Display only total number of words in a file with file name

wc -c Display only total number of characters in a file with file name

7) mkdir

Create new directory(s).

$ mkdir CO

This command creates new directory with name CO.

$ mkdir CO IT

This command creates two new directory having name CO and IT under the current
directory.

8) rmdir

Remove existing directory.

$ rmdir CO

This command removes the directory with name CO if it is empty.

$ rmdir CO IT

Removes existing directory with name CO and IT if they are empty.

9) cd

Change directory

$ cd CO

Change current directory to CO directory.

$ cd /home/student/s1

Change current directory to s1 which is under /home/student.

$ cd ..

Change directory to parent disrectory.

Introductory Linux Workshop 4


SCET, Surat
20th March 2009
10) pwd

Prints Present working directory.

$ pwd

/home/student/user1

This command displays the directory you are working in. For the above output, we can
say that we are in directory user1 which is under subdirectory student under directory
home. And home is under root /.

11) Pg

Display file pagewise

$ pg abc.txt

If you have a file that is a large text file, and if you wanted to go through it without
using an editor it would be very difficult. To do so, you can use pg command.

After displaying one screenful of text, the system will pause and let you read the text.
Once you are through, press enter key and the next screenful will be displayed. If oyu
press q, the system will come out of the pg command and display system prompt.

12) echo

Display argument

This command displays the argument on the screen.

$ echo How r you

Hor r you

Echo can also display content of variable if the variable name is preceded with a $ .

$ echo $HOME

This will display value of environment variable HOME.

13) ps

Display process status.

$ ps
Introductory Linux Workshop 5
SCET, Surat
20th March 2009
This command will display the status of all the currently running process. It will
display four basic information. That is PID (Process Identifier), TTY (Terminal
controlling the process), TIME(Execution time), COMD (The command).

14) date

Display/set system date & time

$ date

This command is used to get system date and time.

$ date [MMddhhmmyy]

This command is used to set system date. Here, MM is Month, dd is Date, hh is Hour,
mm is Minute yy is Year

15) cal

Display Calender.

$ cal 3

Used to get calendar of 3rd month of the current year.

$ cal 2009

Display full calendar of 2009.

16) who

list logged in users.

$ who

This command will list out all user who have currently logged in including yourself.

The output displays four column output : user name, terminal number, date and time
of login.

17) who am i

This command display the same output as who. But it includes the detail about you
only.

18) grep
Introductory Linux Workshop 6
SCET, Surat
20th March 2009
pattern search

This command is useful to search some pattern from file.

$ grep hello file1

This will display all the lines from files having the pattern(word) hello.

We can also use regular expression with grep command. Regular expression contains
wild cards (*,? etc).

$ grep *ll* file1

This command will display all lines having words with ll in them like hell, hello,
smell, balloon etc.

19) sort

Sort file contents

Sort files base on one key field if your file contains records. Otherwise, it will sort
files based on first character on each line.

$ sort file1

when the number of fields are more than one, the key fields are denoted as number in
command.

$ sort +1 -2 o out.txt file1

here +1 is starting key and -2 is end key and out.txt is output file name which you can
use with o option. file1 is source file name.

20) cut

Display selected fields

This command is cut out some character(s) or some field(s) from source file.

$ cut c 2 file1

This command will display or cut out 2nd character from source file file1.

$ cut d f 1 file1

Introductory Linux Workshop 7


SCET, Surat
20th March 2009
This command will cut out 1st field from source file file1. We need to provide filed
separator with d option. Here we are assuming (single space) is available as field
separator in out source file.

21) comm

File Comparison

This command is used to compare two files and it generated three column output.
First column shows the unmatched content from first file, second column shows the
unmatched content from second file and last column shows the common contents
from both files.

$ comm file1 file2

22) cmp

File Comparison

This command compares the files and reports at which point the files differ. The
output is in the form of bytes and line number.

$ cmp file1 file2

23) chmod

Change Mode of file.

Mode of file means the mode in which we can access the file. Using this command
we can change the permission of the file.

In Unix/Linux, any file is having three types of permission (read, write, execute).

Also three types of users are available : Owner, Group and Other

File access privileges are in following format

r w x r w x r w x

User Group Others

For read the privilege is 4, for write the privilege is 2 and for execute the privilege is
1.

Now to give write permission to Group users on file file1 , we need command

Introductory Linux Workshop 8


SCET, Surat
20th March 2009
$ chmod g+w file1 OR $ chmod 020 file1

To give all permission to all users

$ chmod ugo+rwx file1 OR $ chmod 777 file1

24) passwd

Change User Password

$ passwd

This command will prompt for new password.

25) expr

To perform arithmetic operation (+, -, *, /), this command is useful.

$a=20

$b=10

$expr $a + $b

30

$expr $a /* $b

200

Here, * is a wildcard character, so to perform a special operation (i.e. multiplication)


it is necessary to use escape character(/) before this *.

Introductory Linux Workshop 9


SCET, Surat
20th March 2009
Shell Programming
Shell is a powerful command Interpreter. The most important aspect of a programming
language is to create variable, use of programming constructs as well as looping
structures like if..else, for loop, while loop etc.

Shell Variable

The shell allows you to define variables. A variable name can begin with any letter or
underscore and can have a total of more than one character. Variable name is case-
sensitive.

e.g. code, emp_name, x, x1 etc..

Assign value to variable

To assign value to a variable in shell programming is very simple. The rule is no space
should be there between the variable name and = sign and the value assigned.

e.g

$name=Ram

If you want white space between the value, value should be enclosed in the string quotes
like

$name=Ram Kumar

Display value of variable

Introductory Linux Workshop 10


SCET, Surat
20th March 2009
To display value of variable we can use echo command.

$echo $name <Ret>

Ram Kumar

$echo My name is $name <Ret>

My name is Ram Kumar

Shell Script

A Shell script is a command or sequence of commands stored in a file which is executed


by typing. Always give an extension .sh to script file. The script file can be created by cat
command or vi editor.

$ sh {filename} <Ret>

The script should be interactive means it must prompt the user to enter the information
needed. Alternatively, the script should accept command line arguments.

In UNIX environment, all command line arguments are known as positional parameters.

The command is always referred to as $0.

The arguments to the command are $1, $2 etc..

The total no. of arguments is $#.

All the arguments will be displayed by $*.

script1.sh

read command

This command is useful to accept user input. Input may be any type string or number. We
can also accept multiple values using single read command.

Script2.sh

set command

The set command is part of the shell and is used very effectively for command
substitution. If a particular command is enclosed in back quotes ` in conjunction with
echo, the echo will display the output of the enclosed command.

Introductory Linux Workshop 11


SCET, Surat
20th March 2009
$echo `who` <Ret>

Output of who command

Now if you type

$set `date` <Ret>

$echo $1 <Ret>

Sat

Here, date command gets executed as

Sat Mar 21 12:30:31 Ist 2009

and shell reads it as

$set Sat Mar 21 12:30:31 Ist 2009

so $1 is Mon

The if Statement

Syntax :

if [ condition ]

then

commands

fi

if statement is first check condition, if the condition is true then it will execute
command given in then part. A space should be there among [ and condition and ].

Script3.sh

The if : else Statement

Syntax :

if [ condition ]
Introductory Linux Workshop 12
SCET, Surat
20th March 2009
then

commands

else

commands

fi

if statement is first check condition, if the condition is true then it will execute
command given in then part otherwise commands under else part will be executed.

Script4.sh

The elif Statement

In your script contains multiple else part, instead of using more number of else you can
use elif statement.

Syntax :

if [ condition ]

then

commands

elif [ condition ]

then

commands

elif [ condition ]

then

commands

else

Introductory Linux Workshop 13


SCET, Surat
20th March 2009
default

fi

Script5.sh

for Loop

Syntax :

for [variable] name [in list of values]

do

commands

done

Here, variable gets value from list of values one by one. For each value of variable
command(s) under do is executed.

Script6.sh

script7.sh

while loop

Syntax :

while [ control command ]

do

commands

done

In the while loop, the commands between do and done will be executed if the
condition is true.

Script8.sh

until loop

Syntax :

Introductory Linux Workshop 14


SCET, Surat
20th March 2009
while [ control command ]

do

commands

done

In the until loop, the commands between do and done will be executed only if the
condition is false.

Script9.sh

For all above construct, condition includes arithmetic/string comparison.

The arithmetic comparison as follows:

Operator Description

-le less than or equal to

-eq equal

-lt less than

-ge greater than or equal to

-gt greater than

-ne not equal to

String comparison

Operator Description

= equal to

!= not equal to

-z Zero length string

-n Non zero length

Introductory Linux Workshop 15


SCET, Surat
20th March 2009
The case Statement

case statement offers multi-way branching depending upon the user input or a value
assigned to a variable from within the program.

Syntax :

case $ option in

pattern-1)

command(s);;

pattern-2)

command(s);;

esac

The value in option is matched with each pattern till a match is found or the esac
statement is encountered.

Script10.sh

Introductory Linux Workshop 16


SCET, Surat
20th March 2009
System Calls
File I/O

1) open function

A file is opened or created by calling the open function.

Syntax :

#include <sys/types.h>

#include<sys/stat.h>

#include <fcntl.h>

int open(const char *pathname, int oflag,[mode]);

Returns : file descriptor if OK, -1 on error

The pathname is the name of the file open or create

The value of oflag is any one from following :

O_RDONLY - Open for reading only.

O_WRONLY - Open for writing only.

O_RDWR - Open for reading and writing.

This constants are available in fcntl.h file. One and only one of these three
constants must be specified. The following constants are optional.

O_APPEND - Append to the end of file on each write.

O_CREATE - Create the file if it doesnt exist.

O_TRUNC - If the file exists, and if the file is successfully


opened for either write-only or read-write, truncate
its length to 0.

program1.c

Introductory Linux Workshop 17


SCET, Surat
20th March 2009
2) create function

A new file can also be created by

Syntax :

#include <sys/types.h>

#include<sys/stat.h>

#include <fcntl.h>

int create(const char *pathname);

Returns : file descriptor opened for write-only if OK, -1 on error

The pathname is the name of the file open or create.

This function is equivalent to

open (pathname, O_WRONLY | O_CREAT | O_TRUNC, mode);

One deficiency with this function is that the file is opened only for writing.

program1.c

3) close function

An open file is closed by

Syntax :

#include <unistd.h>

int close(int filedes);

Returns : 0 if OK, -1 on error

program2.c

Introductory Linux Workshop 18


SCET, Surat
20th March 2009
4) lseek function

Every open file has an associated current file offset. This is non-negative
integer that measures the number of bytes from the beginning of the file.
Read/Write operations normally start at the current file offset and cause the offset
to be incremented by the number of bytes read and written.

By default, offset is 0 when a file is opened.

Syntax :

#include <sys/types.h>

#include <unistd.h>

off_t lseek(int fields, off_t offset, int whence);

Returns : new file descriptor if OK, -1 on error

offset depends on the value of whence

If whence is SEEK_SET, the files offset is set to offset bytes from the
beginning of the file.

If whence is SEEK_CUR, the files offset is set to its current value plus
the offset. The offset is positive or negative.

If whence is SEEK_END, the files offset is set to the size of the file plus
the offset. The offset is positive or negative.

program3.c

5) read function

Data is read from an open file with the read function.

Syntax:

#include <unistd.h>

ssize_t read(int filedes, void *buff, unsigned nbytes);

Returns: number of bytes read, 0 if end of file, -1 on error

Introductory Linux Workshop 19


SCET, Surat
20th March 2009
If the read is successful, the number of bytes read is returned. if the end of file is
encountered, 0 is returned.

The read operation starts at the files current offset. Before a successful return, the
offset is incremented by the number of bytes actually read.

Program2.c

6) write function

Data is written to an open file with the write function.

Syntax:

#include <unistd.h>

ssize_t write(int filedes, const void *buff, unsigned nbytes);

Returns : number of bytes written if OK, -1 on error

Program2.c

7) stat function

Stat function returns the structure of information about the named file.

Syntax:

#include <sys/types.h>

#include<sys/stat.h>

int stat(const char *pathname, struct stat *buf);

Returns : 0 if OK, -1 on error

The first argument is the file name or filename with full path. The second
argument is buffer in which the function returns the status of the file.

struct stat {

mode_t st_mode; // file type

ino_t st_ino; // i-node number

dev_t st_dev; // device number


Introductory Linux Workshop 20
SCET, Surat
20th March 2009
dev_t st_dev; //device number for special file

uid_t st_uid; //use IDof owner

gid_t st_gid; //group ID of owner

off_t st_size; //size of file

time_t st_atime; //time of last access

time_t st_mtime; //time of modification

};

Many other member variables are available with this structure.

Here File types may be any of the following:

Regular file, Directory file, Character special file, Block special file, FIFO,
Socket etc.

We can determine the type of the file using following Macros.

Macro Types of File

S_ISREG() Regular file

S_ISDIR() Directory file

S_ISCHR() Character special file

S_ISBLK() Block special file

S_ISFIFO() FIFO or Pipe file

S_ISLINK() Symbolic link

S_ISSOCK() Socket

Program4.c

8) chmod function

This function allows us to change the file access permission for an existing file.

Introductory Linux Workshop 21


SCET, Surat
20th March 2009
Syntax:

#include <sys/types.h>

#include<sys/stat.h>

int chmod(const char *pathname, mode_t mode);

Returns : 0 if OK, -1 on error

The first argument is the file name or filename with full path. The mode is
specified as the bitwise OR of the constants as follows:

Mode Description
S_IRWXU Read, Write and Execute by User (Owner)

S_IRUSR Read by User (Owner)

S_IWUSR Write by User (Owner)

S_IXUSR Execute by User (Owner)


S_IRWXG Read, Write and Execute by Group

S_IRGRP Read by Group

S_IWGRP Write by Group

S_IXGRP Execute by Group


S_IRWXO Read, Write and Execute by Other

S_IROTH Read by Other

S_IWOTH Write by Other

S_IXOTH Execute by Other

Program5.c

9) remove function

To remove file from the system we can use this function.

Syntax :

Introductory Linux Workshop 22


SCET, Surat
20th March 2009
#include <stdio.h>

int remove (const char * pathname);

Returns: 0 if OK, -1 on error

The argument is the file name or filename with full path.

Program6.c

10) rename function

A file or Directory is renamed with rename function.

Syntax:

#include <stdio.h>

int rename(const char *oldname, const char *newname);

Returns : 0 if OK, -1 on error

Points to remember

1) If oldname specifies a file then we are renaming a file. If newname is exist,


then this function overwrites the existing file. We must have write permission
for the directory containing oldname and for the directory containing
newname, since we are changing both directories.
2) If oldname specifies directory then we are renaming a directory. If newname
is exists, it must refer to a directory and that directory must be empty. If
newname is exist, it is removed and oldname is renamed to newname.

3) If oldname and newname refer to the same file, the function returns
successfully without changing anything.

Program7.c

11) mkdir function

Directory is created using mkdir function.

Syntax:

Introductory Linux Workshop 23


SCET, Surat
20th March 2009
#include <sys/types.h>

#include<sys/stat.h>

int mkdir(const char *pathname, mode_t mode);

Returns : 0 if OK, -1 on error

The first argument is the file name or filename with full path. The mode is same
as mode concept in chmod function.

Program8.c

11) rmdir function

Syntax:

#include <unistd.h>

int rmdir(const char *pathname);

Returns : 0 if OK, -1 on error

The argument is the file name or filename with full path.

Program9.c

12) Reading Directories

Syntax :

# include <sys/types.h>

#include <dirent.h>

DIR *opendir(const char *pathname);

Returns : pointer if OK, NULL on error

The argument is the file name or filename with full path.

Introductory Linux Workshop 24


SCET, Surat
20th March 2009
struct dirent *readdir(DIR *dp);

Returns : pointer if OK, NULL at the end of directory or error

int closedir(DIR *dp);

Returns : 0 if OK, -1 on error

Program

Program10

13) chdir function

We can change the current working directory of the calling process by calling the
chdir function.

Syntax:

# include <unistd.h>

int chdir (const char *pathname);

The argument is the file name or filename with full path.

Program11

14) getcwd function

This function gives you the information about current working directory.

Syntax :

#include <unistd.h>

char *getcwd(char *buf, size_t size);

Returns : buf if OK, NULL on error

We must pass the name of the buffer and its size.

Program12

Introductory Linux Workshop 25


SCET, Surat
20th March 2009
Introductory Linux Workshop 26
SCET, Surat
20th March 2009

You might also like