Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 21

NHCE

MODLE 4
1. Examine the use of ‘set’ command for debugging a shell script. -Komal
Answer:-
Set command: It is used to set or unset specific flags and settings( determines the
behaviour of the script and helps in executing the tasks without any issue.) inside the shell
environment. It can be used to change or display the shell attributes and parameters.

The set command is a built-in Linux shell command that displays and sets the names and
values of shell and Linux environment variables. On Unix-like operating systems, the set
command functions within the Bourne shell ( sh ), C shell ( csh ), and Korn shell ( ksh ).

Syntax:
Set -options arguments

The set command supports the following options:

Option Description

-a use to mark variables that are created or modified or created for export.

-b use to notify the termination of the job.

-e use to exit when the command exits with a non-zero status.

-f it disables the file name generation known as globbing

-h It saves the location of the command where it got looked.

It places all assignment arguments in the environment variable of a command.

-k Exception: It excludes all arguments that precede the command name.

1
NHCE

-m It enables job control

-n It is used to read the commands.

-o It is used for naming the option

It disables the processing of the ‘$ENV’ file and also imports the shell functions.

-p Turned on: when the real and effective user ids do not match.

Option Description

-t It uses to exit from the command after executing a single command

-u It treats unset variable as an error during substitution

-v It prints the shell inpuexecute

It prints the commands and their arguments in the same sequence as they

-x got executed.

-B It performs the Brace expansion by the shell

-C It disallows the existing regular files to be overwritten

-E used when shell functions inherit the ERR trap

-H It enables style history substitution. It is on by default.

2
NHCE

Used when during command execution we don’t want to follow the

-P symbolic links.
-T set this flag, this helps shell functions to inherit the DEBUG trap

For a demonstration of the use of the set command, let’s use some set command.
Set -x command

This option prints the commands in the sequence as they got executed or is mainly used to
do some script debugging..

Code:

Set -x echo Hello echo Romy

Output:

Bar hello Romy

+ echo bar

+ echo hello

+ echo Romy

We can see the commands getting printed after the command execution with the ‘+’ sign.

Set -e command
It terminates the execution when the error occurs.

Codewithout set -e)

3
NHCE

Echo Hello foo

Echo Romy

Output:

Hello Romy

Main.sh: line 14: foo: command not found

‘foo’ is a non-existent command but bash still executed the third line after encountering
the error at the second line. We can use the set command to stop termination.

Codewith set -e)

Set -e echo Hello foo

Echo Romy
Output:

Hello

Main.sh: line 15: foo: command not found

We can see that the third line is not getting printed as the execution got terminated after
the second line.

Piped commands

Set -e command does not work with piped commands.

4
NHCE

Example:

Set -e

Foo | echo “ This is the piped command” echo “executed”

Output:

This is the piped command executed

Main.sh: line 3: foo: command not found

We can see that third line is getting executed, instead of terminating the execution after
the second line.

To overcome this problem, we have to use ‘set -eo pipefail’

Set -eo pipefail

Example:

Set -eo pipefail

Foo | echo “ This is the piped command”

Echo “executed”

Output:

This is the piped command

5
NHCE

Main.sh: line 13: foo: command not found

Set positional parameters using set command

It can be used to assign values to positional parameters. Position of the value referenced
as ${N} where N denotes the position of the parameter.

The $1 is the first positional parameter after the command. The $2 value is the second
parameter, and so on.

Example:

Set apple mango orange guava echo $1

Echo $2 echo $3 echo $4

Output:

Apple mango orange guava

Unset positional parameters

In order to unset the positional parameter, run the set command followed by two
hyphens(set –).

Example:

Set apple mango orange guava

Set – echo $1 echo $2

6
NHCE

Echo “Hello”

Output:

Hello

We can see that nothing is getting printed corresponding to the first two commands to
print positional parameters.

2. Recommend the use of the following UNIX commands- find, chown, ls – d and ls –a.
- Aishwarya
Answer:-

3. Examine the importance of hard link and symbolic link as file attributes. -Adithya
Answer :-
Inode Number:
 Every file is associated with a table that contains all that you could possibly need to
know about the file (Except its name and contents). This table is called the inode and
is accessed by the inode number.
 The inode contains the following attributes of a file:
 File type [regular, directory, etc]
 File permissions [the nine permissions and three more]
 Number of links
 The UID of the owner
 The GID of the group owner
 File size in bytes
 Date and time of last modification
 Date and time of last access
 Date and time of last change of the eye node
 An array of pointers that keep track of all disk blocks used by the file
 Neither the name of the file nor the inode number is stored in the inode. It’s the
directory that stores the inode number along with the file name.
 The ls command reads the inode to fetch a file’s attributes and it can list most of them
using suitable options, one of them is the -i option that tells you the inode number of a
file.
 Eg: $ls -il filename
 9059 -rw-r--r-- 1 kumar metal 51813 Jan 31 11:15 filename

7
NHCE

o *[The following file has the inode number 9059]

 Hard Links
When a file is copied, both the original and copy occupy separate spaces on the disk.
UNIX allows a file to have more than one name and yet maintain a single copy on disk.
The file is then set to have more than one link i.e., it has more than one name. All names
provided to a single file have one thing in common; they all have the same inode number.
 Creating Hard Links
 A file is linked with the ln (link) command, which takes two filenames as arguments.
The command can create both a hard & a soft link and has a syntax similar to the one
used by cp. The following command (hard) links emp.1st with employee:
 ln emp.1st employee
employee must no exist
 The -i option of ls shows that they have the same inode number, meaning that they are
actual one and the same file.
 $ ls -li emp.1st employee
 29518 -rwxr-xr-x 2 kumar metal 915 May 4 09:58 emp.1st
 29518 -rwxr-xr-x 2 kumar metal 915 May 4 09:58 employee
 The link count, which is normally one for unlinked files, is shown to be two. You can
link a third file to increase it.
 $ln employee emp.dat ; ls -l emp*
 29518 -rwxr-xr-x 3 kumar metal 915 May 4 09:58 emp.dat
 29518 -rwxr-xr-x 3 kumar metal 915 May 4 09:58 emp.1st
 29518 -rwxr-xr-x 3 kumar metal 915 May 4 09:58 emp.employee

 Where to use Hard Links


 Links provide some protection against accidental deletion, especially when they exist
in different directories.
 Because of links, we don’t need to maintain 2 programs as 2 separate disk files if
there is very little difference between them.

Symbolic Links
 Hard links have 2 limitations:
 You can’t have to link file names into file systems. In other words, you can’t link a
filename in the /usr file system to another in the /home file system.
 You can’t link a directory even within the same file system.
 Unlike the hard link, a symbolic link doesn’t have the contents of the file, but simply
provides the file’s pathname that has the contents. Being more flexible, a symbolic
link is also known as a soft link.

 The ln command creates symbolic links also, except that you have to use -s the
option. This time the listing tells you a different story:
 $ ln -s note note.sym
 $ ln -li note note.sym
 9948 -rw-r--r-- 1 kumar group 80 Feb 16 14:52 note
 9952 lrwxrwxrwx 1 kumar group 4 Feb 16 15:07 note.sym -> note
 You can identify symbolic links by the character l (el) seen in the permissions field.
The pointer notation

8
NHCE

 note suggests that note.sym contains the pathname for the filename
note.
 Symbolic links can also be used with relative pathnames. Unlike hard links, they can
also span multiple file systems and also link directories. If you have to link 100
filenames in one directory to another directory, it makes sense to simply link the
directories.

The Directory
 A directory has its own permissions, owners, and links. However, the significance of
the file attributes changes a great deal when applied to a directory. For example, the
size of a directory is in no way related to the size of the files that exist in the directory.
 Read Permission:
o Read permission for a directory means that the list of filenames stored in that
directory is accessible. Since ls reads the directory to display filenames, if a
directory’s read permission is removed, ls command won’t work.
o $ ls -ld progs
o drwxr-xr-x 2 kumar metal 128 Jun 18 22:41 progs
o $ chmod -r progs ; ls progs
o Progs: Permission denied
o total 2

 Write Permission:
o Write permission for a directory implies that you are permitted to create or
remove files in it. To try that out, restore the read permission and remove the
write permission from the directory before you try to copy a file to it.

 unmask: DEFAULT FILE AND DIRECTORY PERMISSIONS


 When you create files and directories, the permissions assigned to them depend on the
system’s default setting. The Unix system has the following default permissions for
all files and directories.
 rw-rw-rw- (octal 666) for regular files.
 rwxrwxrwx (octal 777) for all directories.
 $ umask 022
 This is an octal number that has to be subtracted from the system default to obtain the
actual default. This becomes 644 (666-022) for ordinary files and 755 (777-022) for
directories. When you can create a file on the system, it will have the permissions rw-
r--r--.
 umask is a shell built-in command but it also exists as an external command. A user
can also use this command to set a new default. [$ umask 000 ; umask value of 000
means that you haven’t subtracted anything. All read-write permissions are on. ]

4. Recommend the use of ‘chmod’ command to grant permission for a file with filename
‘myfile’ to different types of users. OR Investigate the UNIX commands used for
granting permissions for a file to different type of users. -Mayuri
Answer :-

9
NHCE

 The chmod command is used to manage file system access permissions in unix. There
are three baisc file system permissions or modes,
 Read(r)
 Write(w)
 Execute(x)
 Each mode can be applied to these classes:
 User(u) : The user is the account that owns the file.
 Group(g) : The group that owns the file may have other accounts in the system as
members.
 Others(o) : All other accounts on the system.
 The modes of the files and directories can be viewed using ls -l command.
 Syntax: chmod [references][operator][modes] filename
 Refernces- shorthand ( u,g,o) of each class.
 Operator- determines whether to add(+) or removes(-) permissions.
 Modes- the modes are read(r),write(w),execute(x).
 Example:
 chmod u+rwx myfile #adds all permission for the user.
 chmod g+rw myfile #adds read and write permission to group.
 chmod o+r myfile #adds only read permission to others.
 chmod u-x myfile #removes execute permission .

5. Decide the set of commands that may be used in a shell script to read a file name entered
by the user and output the file’s properties. -Chandana K
 Answer :-
 echo "enter a file name"
 read fname
 if [ -f $fname ]
 then
 echo "Display the file properties"
 ls -l $fname
 dis=`ls -l $fname | tr -s "" | cut -c1-10`
 echo "file properties are:$disp"
 else
 echo "enter a valid filename"
 fi
 The set commands used in a above shell script are:
 1.echo command
 2.ls command
 3.tr command
 4.cut command
 echo command:
 echo command prints the given input string to output.
 Syntax:
o echo[options..] [string]
 Options:

10
NHCE

 -n  do not output the trailing newline.


 -e  enable interpretation of blackslash-escaped character listed
below.
 -E  display interpretation of those sequences in strings.
ls command:
 ls command list the files and directories under current working
directory.
 Syntax:
 ls[options]…[file]
 Options:
 -l  list all files,directories and their mode, Number of links, owner of
file, file size, modified date and time and filename.
 -t  list in order last modification time
 -d  list directory files instead of contents.
3.tr command:
 The tr command in unix is a command line utility for translating or
deleting characters.tr stands for translate.
 Syntax:
o tr[options] set1 [set2]
 Options:
 -ccomplements set of characters in a string
 -ddeletes characters in the first set from the output.
 -sreplaces repeated characters listed in the set1 with single
occurance.
4.cut command:
 Cut command is used to cut the selected fields of each line of a file.The
cut command uses delimeters to determine where to split fields.
 Syntax:
o cut[options]
 Options:
 -c specifies character positions.
 -b specifies byte positions.
 -d flags specifies delimeters and fields.

6. Investigate the use of the following keywords/commands in UNIX - shift, heredoc


redirections, exec and eval. – Parth Dobaria
Answer:-
 Shift :
o Shift is a built in command in bash which after getting executed, shifts/move
the command line arguments to one position left.
o The first argument is lost after using shift command.

11
NHCE

o This command takes only one integer as an argument.


o This command is useful when you want to get rid of the command line
arguments which are not needed after parsing them.

 SYNTEX :
 shift n
o Here, n is the number of positions by which you want to shift command-line
arguments to the left if you do not specify, the default value of n is assumed
to be 1 i.e. shift works the same as shift 1.

 EXAMPLE :
 echo "The arguments are: $*"
 echo "The First Argument is: $1"
 shift 2
 echo "The First Argument After Shift 2 is: $1"
 shift
 echo "The First Argument After Shift is: $1"

 OUTPUT:
 sh sampleshift.sh G1 G2 G3 G4
 The arguments are: G1 G2 G3 G4
 The First Argument is: G1
 The First Argument After Shift 2 is: G3
 The First Argument After Shift is: G4

Heredoc (<<) :
o A block of code or text which can be redirected to the command script or
interactive program is called here document or HereDoc.
o When the coder needs less amount of text data, then using code and data in the
same file is the better option, and it can be done easily by using here-
document in the script.
o Without scripting language, here document can also be used in various high-
level languages like php, perl, etc.

o To use here-document in any bash script, you have to use the symbol <<
followed by any delimiting identifier after any bash command and close the
HereDoc by using the same delimiting identifier at the end of the text.

12
NHCE

SYNTEX :
o [COMMAND] << 'DELIMITER'
 HERE-DOCUMENT
 DELIMITER

o Example:
o When the heredoc is used in any script, it is necessary to keep the same name
for the starting and ending delimiter. Suppose the command is `cat` and the
heredoc delimiter is EOF.

 cat << EOF


 The current working directory is: $PWD
 You are logged in as: $(whoami)
 EOF

o OUTPUT:
 The current working directory is: /home/linuxize
 You are logged in as: linuxize

Exec :
o On Unix-like operating systems, exec is a built in command of the Bash shell.
o It allows you to execute a command that completely replaces the
current process.
o The current shell process is destroyed, and entirely replaced by the command
you specify.
o exec is a critical function of any Unix-like operating system.
o Traditionally, the only way to create a new process in Unix is to fork it.
o The fork system call makes a copy of the forking program. The copy then
uses exec to execute the child process in its memory space.

SYNTAX :
o exec [-c] [-l] [-a name] [command [arguments ..]] [redirection ...]

-a name Pass the string name as the zeroth argument to command. This


option is available in bash versions 4.2 and above. When used,
it will execute command, and set the special

13
NHCE

shell variable $0 to the value name, instead of command. For


more information, see bash special parameter 0.
-c Execute command in an empty environment.
-l Insert a dash at the beginning of the zeroth argument. This can
start a login shell via exec. For more information about login
shells, and bash's requirements about how they may be
invoked, see shell invocation in bash.
command The command to be executed. If you do not specify a
command, exec can still provide redirection.
arguments The arguments for the command you'd like to execute.
redirection Any redirection for the command. If no command is specified,
redirection applies to the current shell.

Eval:
o eval is a built-in Linux command which is used to execute arguments as a
shell command.
o It combines arguments into a single string and uses it as an input to the shell
and execute the commands.

o Syntax:
o eval [arg ...]

Example:
 ~$ CD=”cd Desktop”
 ~$ Eval $CD
 ~/Desktop$

7. The UNIX find command recursively examine directory tree based on several parameters.
Justify the statement. (Hint: You need to write the usage, syntax and examples with all
switches used in find command with explanation). - Nimit
Answer :-
The find command in UNIX is a command line utility for walking a file hierarchy. It can be
used to find files and directories and perform subsequent operations on them. It supports
searching by file, folder, name, creation date, modification date, owner and permissions. By
using the ‘-exec’ other UNIX commands can be executed on files or folders found.
find searches the directory tree rooted at each given file name by evaluating the given
expression from left to right, according to the rules of precedence, until the outcome is known
(the left hand side is false for and operations, true for or), at which point find moves on to the
next file name.

14
NHCE

Syntax :
$ find [where to start searching from]
[expression determines what to find] [-options] [what to find]
Options :
 -exec CMD: The file being searched which meets the above criteria and returns 0 for
as its exit status for successful command execution.
 -ok CMD : It works same as -exec except the user is prompted first.
 -inum N : Search for files with inode number ‘N’.
 -links N : Search for files with ‘N’ links.
 -name demo : Search for files that are specified by ‘demo’.
 -newer file : Search for files that were modified/created after ‘file’.
 -perm octal : Search for the file if permission is ‘octal’.
 -print : Display the path name of the files found by using the rest of the criteria.
 -empty : Search for empty files and directories.
 -size +N/-N : Search for files of ‘N’ blocks; ‘N’ followed by ‘c’can be used to
measure size in characters; ‘+N’ means size > ‘N’ blocks and ‘-N’ means size < 'N'
blocks.
 -user name : Search for files owned by user name or ID ‘name’.
 \(expr \) : True if ‘expr’ is true; used for grouping criteria combined with OR or
AND.
 ! expr : True if ‘expr’ is false.
Consider the following tree hirerachy :

1. Search a file with specific name.

15
NHCE

$ find ./GFG -name sample.txt


It will search for sample.txt in GFG directory.
Output :

2. Search a file with pattern.


$ find ./GFG -name *.txt
It will give all files which have ‘.txt’ at the end.
Output :

16
NHCE

3. How to find and delete a file with confirmation.


$ find ./GFG -name sample.txt -exec rm -i {} \;
When this command is entered, a prompt will come for confirmation, if you want to delete
sample.txt or not. if you enter ‘Y/y’ it will delete the file.
Output :

4. Search for empty files and directories.


$ find ./GFG -empty

17
NHCE

This command find all empty folders and files in the entered directory or sub-directories.
Output :

5. Search for file with entered permissions.


$ find ./GFG -perm 664
This command find all the files in the GFG directory or sub-directory with the given
permissions.
Output :

18
NHCE

6. Search text within multiple files.


$ find ./ -type f -name "*.txt" -exec grep 'Geek' {} \;
This command print lines which have ‘Geek’ in them and ‘-type f’ specifies the input type is
a file.
Output :

In short, Find Command in Unix returns all files below the current working directory.
Further, find command allows the user to specify an action to be taken on each matched file.

8. Explain the file attribute support in UNIX. (Hint: File permission , directory permission.)
– Madhu Shree
Answer :-
File Permissions :

There are three kinds of permissions : 

 Read ( r ) : Grants the capability to read, i.e., view the contents of the file .

 Write ( w ) : Grants the capability to modify, or remove the content of the file.

 Execute ( x ) : Users with execute permissions can run a file as a program.


 Similarly, there are three classes of permissions:
 Owner :  The file's owner

19
NHCE

 Group : Users who are in the file's group

 Other : Everybody else on the system (except the superuser)


 Directory Permissions :

 Directory permissions are listed and organized in the same manner as any other file.

 Read : Access to a directory means that the user can read the contents. The user can
look at the filenames inside the directory.
 Write : Access means that the user can add or delete files from the directory.
 Execute : Executing a directory doesn't really make sense, so think of this as a
traverse permission. A user must have execute access to the bin directory in order to
execute the ls or the cd command.

 Changing Permissions :

To change the file or the directory permissions, we use the chmod (change mode)


command.

Number Octal Permissions Representation Ref

0 No permission ---

1 Execute permission --x

2 Write permission -w-

3 Execute and write permission -wx

4 Read permission r--

5 Read and execute permission r-x

6 Read and write permission rw-

7 All permissions rwx

20
NHCE

 Basic permissions are :

rwx r-x - - -

   
Access granted to non-owner,non-group
( Others )

Access granted to group members

Access granted to file’s owner ( User )

File type ( file , directory , etc )

Example 1 :

$ls -l
rw- r-x --x 2 ABC AB 1024 09:02:10 File 1

2 : No of links
ABC : Owner
AB : Group
1024 : Size of file
09:02:10 : Date & Time
File 1 : Name of file

Example 2 : Using chmod command

$ chmod 755 File 1


$ls -l File 1
rwx r-x r-x 2 ABC AB 1024 09:02:10 File 1
$chmod 743 File 1
$ls -l File 1
rwx r-- -wx 2 ABC AB 1024 09:02:10 File 1
$chmod 043 File 1
$ls -l File 1
--- r-- -wx 2 ABC AB 1024 09:02:10 File 1

21

You might also like