Top Banner
J.E.D.I.  1 Basic commands and Scripting  1.1 Objectives The objective of this chapter is to teach basic knowledge of the Solaris terminal and create basic bash scripts. 1.2 Chapter Outline Terminal Help commands Navigating the file sstem !odifing the file sstem "edirecting o#tp#t Environment variables $asic Scripts %dvanced Scripting %dministration  1.3 The terminal &earning an operating sstem goes beond knowledge of the graphical #ser interface. The graphical #ser interface is eno#gh for reg#lar #ser. The terminal allows for the e'ec#tion of powerf#l commands. This chapter teaches some of the basic commands of the Solaris terminal as well as gives an introd#ction to shell scripting. (o# can open a terminal b right)clicking on the desktop and selecting *pen Terminal. The prompt is where terminal commands are entered. +or o#r e'ample, we will represent the terminal command with a - sign. (o# do not have to tpe the - sign when o# are entering commands. In a later part of this chapter, o# will be asked to switch to the root #ser. The root #ser, also known as the s#per#ser, is the administrator of o#r comp#ter, with access to commands which have sstemwide effect. The terminal prompt for the s#per#ser changes to reflect this, and to represent the s#per#ser, we will #se the sign. (o# do not have to tpe the sign when entering commands. /ommands as well as filenames in Solaris are cas e sensitive. "#nn ing the ls command, for e'ample, as &S or &s will not e'ec#te the ls command at all.  1.4 Help commands Each terminal command in Solaris comes with help doc#mentation. (o# can access this b r#nning the man command followed b the command that o# wo#ld like to ask help on. +or e'ample, to ask help on the ls command, simpl tpe. $ man ls *perating Sstems 0
17

Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

Mar 08, 2016

Download

Documents

Basic Commands and Scripting
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

7/21/2019 Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-3-basic-commands-and-scripting 1/17

J.E.D.I.

 1 Basic commands and Scripting

 1.1 ObjectivesThe objective of this chapter is to teach basic knowledge of the Solaris terminal and createbasic bash scripts.

1.2 Chapter Outline● Terminal

● Help commands

● Navigating the file sstem

!odifing the file sstem● "edirecting o#tp#t

● Environment variables

● $asic Scripts

● %dvanced Scripting

● %dministration

 1.3 The terminal

&earning an operating sstem goes beond knowledge of the graphical #ser interface. Thegraphical #ser interface is eno#gh for reg#lar #ser. The terminal allows for the e'ec#tion ofpowerf#l commands. This chapter teaches some of the basic commands of the Solaris terminalas well as gives an introd#ction to shell scripting.

(o# can open a terminal b right)clicking on the desktop and selecting *pen Terminal.

The prompt is where terminal commands are entered. +or o#r e'ample, we will represent theterminal command with a - sign. (o# do not have to tpe the - sign when o# are enteringcommands.

In a later part of this chapter, o# will be asked to switch to the root #ser. The root #ser, alsoknown as the s#per#ser, is the administrator of o#r comp#ter, with access to commandswhich have sstemwide effect. The terminal prompt for the s#per#ser changes to reflect this,

and to represent the s#per#ser, we will #se the sign. (o# do not have to tpe the signwhen entering commands.

/ommands as well as filenames in Solaris are case sensitive. "#nning the ls command, fore'ample, as &S or &s will not e'ec#te the ls command at all.

 1.4 Help commandsEach terminal command in Solaris comes with help doc#mentation. (o# can access this br#nning the man command followed b the command that o# wo#ld like to ask help on. +ore'ample, to ask help on the ls command, simpl tpe.

$ man ls

*perating Sstems 0

Page 2: Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

7/21/2019 Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-3-basic-commands-and-scripting 2/17

J.E.D.I.

(o# can navigate thro#gh the man#al #sing the #p and down kes. To 1#it, o# can press 1.

Some commands come with their own help o#tp#t. Invoking this varies per command.

 1. !avigating the "ile s#stem

 1.5.1 ls command 

The ls command lists files in o#r c#rrent director. If o# r#n ls now, it will show o# the filesin o#r home director.

(o# can also view selected files #sing ls. If the file is not there, then the command does notprod#ce an o#tp#t.

The ls command can be #sed with wildcards. 2sing ls with wildcards allows o# to view filesthat match a certain criteria. The following are the commonl #sed wildcards

● 3 ) represents 4 or more characters. +or e'ample, ls a3 will list all files which begin withthe letter a. ls 3.java lists down all files that end with .java, or all java files. ls 3 listsdown all files, which is also its defa#lt behavior.

● 5 ) represents a single character. +or e'ample, ls 5a5 will match all files which has an a

in the middle

%s with most commands, ls can be given additional options, specified b the min#s sign. +ore'ample, to view files in long format, which shows additional file information, o# can #se the)l option. To view all files 6incl#ding hidden files7 o# can #se the )a option. To do both, o#can tpe ls )a )l, or better, ls )al.

"#nning the ls command with the )a option lists down hidden files. Hidden files are filenamesthat begin with a period. +or e'ample, the .bashrc script is a hidden file that r#ns whenever aterminal is opened. (o# can also create hidden files simpl b #sing a period at the start ofo#r file

Some options consist of words instead of single letters. Some options ma also re1#ire someparameters, which are often specified with an e1#al statement. See the following e'ample,which lists down all files, and the additional )sort option, with the parameter si8e which viewsall files according to si8e.

$ ls -al –sort=size

There are man other options for the ls command which o# can check o#t b viewing the manpage.

1.5.2 File permissions

% short description of the o#tp#t of ls )l is necessar at this point. In partic#lar, we will disc#ssfile permissions.

*perating Sstems 9

Page 3: Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

7/21/2019 Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-3-basic-commands-and-scripting 3/17

J.E.D.I.

The first blank in the access control list describes what tpe of file is being listed. Having ablank there means that it is a reg#lar file. % d indicates a director, an l or s indicates a hard orsoft link to another file respectivel. +or devices, b indicates that the file represents a blockdevice while c indicates that the file points to a character device.

There are three possible permissions. +or a file to be readable, it m#st have the r permission.If a #ser wishes to change the file, then the #ser m#st have the w permission. If the file can bee'ec#ted, then the #ser e'ec#ting the file m#st have the ' permission.

The access control list is divided into three parts. The first three characters is the #serpermission list indicating if the #ser can read, write or e'ec#te the file. The ne't threecharacters is the gro#p access permission while the final three letters indicate the permissionof non)gro#p members.

/onsider the following access permission: rw'rw)r))

The first three letters determine the #ser permission. Having r there means that the file isreadable b the file creator. The w means that the file can be written 6its not read)onl7. The '

permission means that the file is e'ec#table. +or o#r e'ample, the #ser can read, write ande'ec#te the file.

2sers in 2NI; sstems can belong to #ser gro#ps, and the ne't three characters determinewhat permissions other people in the same gro#p as the file creator can do. % missingpermission 6in this case, the ' permission7 means that the other gro#p members cannotperform that operation on the file 6i.e. *ther gro#p members cannot e'ec#te this file7.

+inall, the last three characters stand for the permissions of people belonging to other gro#ps.%s can be seen, with the w and ' permissions blanked o#t, other sstem #sers can onl readthe file.

+ile permissions can be changed with the chmod command. The chmod command accepts twoparameters, the filename of the file o# want changed, and the new permissions specified#sing three octal digits.

If an octal digit is converted into binar, then the binar n#mber wo#ld consist of three digits.+or the access control list, 0 means that permission wo#ld be set, 4 means that thatpermission will not be given. /hmod needs three octal digits, the first digit for the #serpermissions, the second for the gro#p permissions, and the third for the permissions for other#sers.

+or e'ample, if we have a file called hello.t't, the permission rw'rw)r co#ld be set b chmod<=> hello.t't 6000 004 0447. ?ermission rw)r)'r)) co#ld be set b chmod =@> hello.t't 6004040 0447.

*perating Sstems A

Page 4: Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

7/21/2019 Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-3-basic-commands-and-scripting 4/17

J.E.D.I.

 1.5.3 cd and pwd command 

%s was mentioned earlier, o# are c#rrentl in o#r home director. To find o#t what o#rc#rrent director is, o# can r#n the pwd command, which stands for present workingdirector.

$ pwd/export/home/alice

The Solaris file sstem starts from the root director, or the B director. To get to o#r homedirector from the root director, o# first have to go to the e'ports director, then to thehome director #nder that, and then finall to the director with the same name as o#r #sername.

(o# ma change o#r director with the cd command, followed b the name of the directorthat o# want to go to. Since there arenCt an directories in the home director, let #s first goto the root director 6B7 as shown b the following command.

$ cd /

If o# r#n the ls command there, o# will be shown the top level director of the lin#' filesstem. The following diagram shows a tpical file sstem for 2NI; based sstems like Solaris.

To go to, for e'ample, the etc director, again o# can r#n the cd command, followed b thedirector o# want to go to

$ cd etc

If o# r#n pwd again, it will show that indeed, o# are in the etc director. (o# can go into the

*perating Sstems >

Page 5: Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

7/21/2019 Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-3-basic-commands-and-scripting 5/17

J.E.D.I.

s#bdirectories of etc if o# wish to view the files that are there.

To go #p one step, o# can tpe the following command

$ cd ..

The do#ble period is a reference to the parent director of the c#rrent director. Th#s, if o#were in the etc director, then o# wo#ld go back one step #p to the root director. The singleperiod is #sed to specif the c#rrent director 6we shall #se this later with other commands7

There are two was to specif a director. (o# can specif the relative director name as wedid with etc. (o# can specif more than one director. +or e'ample, to go from the rootdirector to the defa#lts director in the etc director, o# can sa

$ cd etc/defaults

(o# can also specif the absol#te director name. The absol#te director name is the completename of the director path starting from the root director. +or e'ample, from an director in

o#r sstem, o# can go back to o#r home director via the command$ cd /export/home/<username>

If o#r #sername is alice, then o#r command wo#ld be

$ cd /export/home/alice

In addition, simpl tping cd will place o# directl in the home director.

 1.5.4 The Solaris file system

%s we have beg#n navigating the file sstem, we shall ret#rn to the root director and listdown the directories of the Solaris sstem. %ltho#gh there are man directories, and thesedirectories ma change depending on o#r installation, the following are the commondirectories and their #se

●  Be'portBhome The home director of all #sers in the sstem. Some machines ma

have this as the Bhome director

●  B#sr The e'ec#table files of o#r Solaris sstem

●  Betc /onfig#ration files are stored here

●  Bvar ariable director. This is where temporar files s#ch as logs are stored

●  Bproc % special director of o#r file sstem which displas the applications c#rrentl

r#nning in o#r sstem as files

●  Bmnt Directories where removable media, s#ch as flopps, /Ds, and flash disks are

mo#nted.

●  Bdev devices are represented as files in Solaris and placed in this director.

1.5.5 du and df 

The d# 6or disk #sage7 command lists down how m#ch space is being #sed b files in aspecified director, incl#ding s#b)directories. It is often #se with the )h command, to give a

h#man readable o#tp#t.$ du -h /etc

*perating Sstems @

Page 6: Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

7/21/2019 Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-3-basic-commands-and-scripting 6/17

J.E.D.I.

  5K /etc/certs

  5K /etc/cron.d

  5K /etc/crypto/certs

  K /etc/crypto/crls

  K /etc/crypto

  !"K /etc/default  "K /etc/de#ices

...

5! /etc

The df command stands for disk free. "#nning df displas #sage statistics for all disks in thesstem. &ike d# it is #sed with )h which gives h#man readable o#tp#t

$ df -h

%ilesystem size used a#ail capacity ounted on

/de#/ds&/c't'd's' "( ".)( *."( "'+ /

/de#ices 'K 'K 'K '+ /de#ices

ctfs 'K 'K 'K '+ /system/contract

proc 'K 'K 'K '+ /procmntta, 'K 'K 'K '+ /etc/mntta,

swap .( . .( + /etc/s#c/#olatile

o,fs 'K 'K 'K '+ /system/o,ect

fd 'K 'K 'K '+ /de#/fd

swap .( 'K .( '+ /tmp

swap .( )K .( + /#ar/run

/de#/ds&/c't'd's0 *( ).( ( "+ /export/home

 1.5.6 The find command 

To look for a file, o# can #se the file command. The find command starts looking for afilename 6specified b the )name option7 from the given director, rec#rsivel looking thro#gh

all the s#bdirectories. (o# can even #se wildcards with this command.+or e'ample, we look for all files in the Betc director that start with the word profile

$ find /etc -name profile1

%gain, there are man other options with the find command which o# can read #p on #singthe man command.

1.$ %odi"#ing the "ile s#stemNote that at this stage o# can onl make changes to o#r home director. *nl the root #sercan perform changes to other directories in the sstem.

1.6.1 File copying

(o# can cop files with the cp command. The cp command has two arg#ments, the so#rce fileand the destination file. Note that these filenames can contain directories as well as wildcards.

+or e'ample, if o# want to cop the passwd file in the Betc director to o#r c#rrent director,o# can sa

$ cp /etc/passwd .

If o# want to cop all files in the Betc director to o#r home director, o# can sa

$ cp /etc/1 /export/home/<username>

If the destination is a filename and not a director, then the cp command copies the file and

*perating Sstems =

Page 7: Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

7/21/2019 Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-3-basic-commands-and-scripting 7/17

J.E.D.I.

renames it. +or e'ample, if o# have a te't file named a.t't and o# want to make a cop of itinto a file named b.t't, o# can sa

$ cp a.txt ,.txt

(o# ma cop entire directories b #sing the )r option, which stands for rec#rsive coping."ec#rsive coping incl#des even s#bdirectories of the specified so#rce director. +or e'ample,if o# want to cop all of the contents of Betc to o#r home director, then o# can sa

$ cp -r /etc /export/home/<username>

*nce the coping has finished, o# can take a look at o#r home director and see a new etcdirector there.

To move files, o# can #se the mv command. The mv command has similar options andf#nctionalit as the cp command, e'cept that it deletes the so#rce after the file6s7 ordirectories have been moved.

+or e'ample, we move o#r a.t't to c.t't

$ m# a.txt c.txt

Deleting files j#st accepts a single parameter, the file that o# want to delete. +or e'ample, ifwe want to delete c.t't, we can sa

$ rm c.txt

rm can also accept m#ltiple files, as in

$ rm file file

rm can be #sed with wildcards. +or e'ample, the following deletes all files in, for e'ample, atemporar director in o#r home folder.

$ rm /export/home/<username>/temp/1

Note that this deletes onl files. Director deletion will be disc#ssed later.

1.6.2 Directory creation and deletion

To create directories, o# can #se the mkdir command. +or e'ample, to create a directornamed lesson0, o# can sa

$ m&dir lesson

This creates a new s#bdirector in o#r c#rrent director. (o# ma also specif a complete

path from the root. +or e'ample, what if o# want to make an e'ercise0 director insidelesson0:

$ m&dir /export/home/<username>/lesson/exercise

To delete directories, o# can #se the rmdir command. The rmdir command can accept arelative pathname or an absol#te pathname. +or e'ample, if o# want to delete the e'ercise0director, o# can sa

$ rmdir /export/home/<username>/lesson/exercise

Note that the rmdir command can onl work if the director is alread empt of files, so o#ma need to #se the rm command there first to remove all files, and rmdir to remove alldirectories before o# are able to delete that director.

However, there is a shortc#t to this. (o# can #se the rm command with the option )rf, )r for

*perating Sstems <

Page 8: Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

7/21/2019 Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-3-basic-commands-and-scripting 8/17

J.E.D.I.

rec#rsive 6which means delete even s#bdirectories7, and )f for forced deletion. The followinge'ample deletes the lesson0 director even if it has content inside it.

$ rm -rf /export/home/<username>/lesson

Note that this is a ver dangero#s command. If o# are in the root director and sa rm )rf .,o# wo#ld end #p deleting the entire file sstem. Note that there is no eas wa to #ndeletefiles in Solaris, as s#ch, proceed with ca#tion when #sing this command.

1.& 'iping output to a program or "ile

 1..1 !edirections

The o#tp#t of commands can be redirected to a file. +or e'ample, listing the contents of the Betc command ma fill the entire screen, so perhaps o# wo#ld like to have this saved into afile for viewing with a te't editor later. To do this, simpl place the F operand after thecommand and indicate the filename where the o#tp#t is to be saved.

$ ls -l /etc > list.txt

*nce the e'ec#tion is done, o# can view the o#tp#t of the file via an te't editor or to save itfor later analsis. This redirection can be made to work with an command.

The F operand overwrites the old contents of the destination file. To append o#tp#t to a file,o# can #se the FF operand. +or e'ample, if we want to add more files to o#r list.t't, we canwrite:

$ ls -l /usr >> list.txt

The append command is often #sed for logging, where the o#tp#t of a program, s#ch asoperating sstem messages, is stored over a long period of time.

%s a final note, we have a command called echo which simpl prints o#t what the parameterwas passed in. +or e'ample:

$ echo 23ello world42

3ello world4

(o# can redirect the echo command to add some organi8ation to o#r logs. +or e'ample:

$ echo 2istin6 the contents of /etc2 > list.txt

$ ls -l /etc >> list.txt

$ echo 2istin6 the contents of /usr2 >> list.txt

$ ls -l /usr >> list.txt

If o# want to totall s#ppress the o#tp#t of a command, o# can redirect it to a special filecalled BdevBn#ll. This is a special file that simpl discards an o#tp#t sent to it.

*#tp#t s#ppression co#ld be #sed to change the wa a program behaves. GeCll see thise'ample later on.

+or e'ample, the following command totall s#ppresses o#tp#t of the ls command$ ls /etc > /de#/null > /de#/null

 1..2 "rror streams

2NI; sstems differentiate between o#tp#t stream and an error stream. *#tp#t stream is o#rreg#lar o#tp#t while the error stream is for program errors.

*perating Sstems

Page 9: Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

7/21/2019 Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-3-basic-commands-and-scripting 9/17

J.E.D.I.

?rogramming lang#ages often provide commands to send information to the error stream. Javaprovides two different o#tp#t commands. Sstem.o#t.println67 for reg#lar o#tp#t andSstem.err.println67 for error o#tp#t

(o# can see the error stream at work if o# r#n the following command:

$ ls nosuchfile.txt > output.txtls7 nosuchfile.txt7 8o such file found

The ls error is sent to the error stream, not to o#tp#t.t't

The F operand redirects onl the o#tp#t stream

If o# want to redirect the error stream as well, o# can #se the 9F operand

$ ls nosuchfile.txt > output.txt > error.txt

 1..3 #sing more and less

(o# can also #se the more command to view the contents on the screen. The more command

pa#ses the o#tp#t so o# can view one screenf#l at a time. (o# chain the more command withls #sing the pipe 67 command.

$ ls -l /etc 9 more

The more command, however, is limited to onl forward movement. The less command, similarto more, allows for backward and forward viewing of the o#tp#t, 6i.e. &ess is more7

$ ls -l /etc 9 less

 1.( )nvironment variablesEnvironment variables are variables that are defined b the operating sstem. ariables areidentified b the - sign in front of them. +or e'ample, the -?%TH variable lists down thedirectories that the terminal looks for e'ec#table files when the #ser r#ns a command. To findo#t the val#e of o#r path variable, o# can sa

$ echo $:;3

*ther e'amples of environment variables are the -H*!E, -2SE", and -?GD which show o#rhome director, c#rrent #ser name and present working director respectivel. (o# can find o#ttheir val#es b r#nning the echo command. The following echo command shows these val#esas well as show how o# can mi' string messages with variables in a single echo command.

$ echo 23ello4 y username is 2 $?@ 2. A call the 2 $3B? 2 directory as

my home.2

Hello m #sername is alice. I call the Be'portBhomeBalice director as m home.

(o# can #se both single and do#ble 1#otes in the echo command. The difference is that placinga variable inside a do#ble 1#ote wo#ld e'pand the val#e of the variable.

$ echo 23ello4 y name is $?@2

3ello4 y name is $?@

$ echo C3ello4 y name is $?@C

3ello4 y name is alice.

%s can be seen, placing the - sign in do#ble)1#oted echo means that the word after it will beconsidered as a variable. To be able to print the - sign, simpl p#t a backslash in front of the -sign 6i.e. K-7.

(o# can also define o#r own variables. +or e'ample, o# want to have o#r own #ser defined

greeting, o# can sa at the prompt:

*perating Sstems L

Page 10: Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

7/21/2019 Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-3-basic-commands-and-scripting 10/17

J.E.D.I.

$ 6reetin6=2Duenos dias42

Note that o# donCt have to p#t the - sign if o#Cre assigning a val#e to a variable 6the -shown there is the prompt7. %lso, there sho#ld not be spaces between both sides of theassignment operator. ariable names are also case sensitive.

(o# can now #se o#r variable as o# wo#ld the other environment variables.

$ echo $6reetin6 2 y username is 2 $?@ 2. A call the 2 $3B? 2

directory as my home.2

Duenos dias4 y username is alice. A call the /export/home/alice directory

as my home.

(o# can also change the val#e of e'isting variables. +or instance, if o# want to add o#r homedirector to the path variable to alwas look in o#r home director, o# can sa:

$ :;3=$:;37/export/home/<username>

Note that #ser)defined variables are accessible onl within the terminal where the are

declared. If o# have other open terminal windows, the will be #nable to access o#r #serdefined variable. %lso, once o# close o#r terminal, the variableCs val#e will disappear.

&ater on we will learn how to permanentl store a #ser)defined variable.

1.* Basic Scripts(o# can consider a script to be a file that contains s#ccessive instr#ctions for the terminal.Some sstem tasks involve a s#ccessive chain of simple commands, b placing these in ascript, o#Cll save o#rself some time and effort b e'ec#ting onl a single command.

Scripting also goes beond j#st a chain of commands, most scripting lang#ages have their ownprogramming constr#cts s#ch as if)statements and loops, and can accept #ser inp#t. Ge will

disc#ss basic and advanced scripting in this chapter.

+or this chapter, we will #se the bash scripting lang#age. $ash stands for $o#rne)again shell,which is a revision of the original $o#rne shell. There are other shells, s#ch as ksh or kornshell, or c shell 6csh7, each with different snta'. However, the lessons learned here are easilapplicable to the other shells.

1.$.1 %reating a &ash script 

In o#r previo#s e'ample where we listed down the contents of o#r Betc and B#sr directoriesand placed them in a file called list.t't. $elow is a basic script file that chains these instr#ctionstogether. (o# can #se an te't editor to write this file down. Ge will name o#r file as mscript.

E4/,in/,ash

E this is my first ,ash script.

echo 2istin6 the contents of /etc2 > list.txt

ls -l /etc >> list.txt

echo 2istin6 the contents of /usr2 >> list.txt

ls -l /usr >> list.txt

/omments are preceeded b a sign. However, the first line of o#r script indicates that thisscript is to be r#n with bash, whose e'ec#table file is in the director Bbin.

To e'ec#te this file, we m#st first change its file permissions. To find o#t what o#r scriptCs file

permissions, we can #se the ls )l command.

*perating Sstems 04

Page 11: Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

7/21/2019 Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-3-basic-commands-and-scripting 11/17

J.E.D.I.

$ ls -l myscript

-rw-r--r-- alice alice ! 8o# )7' myscript

The file permissions for mscript are read)writable for the file owner alice and onl readable forall others. To make o#r script e'ec#table, we simpl add the e'ec#table permission to it #singthe chmod command

$ chmod 055 myscript

$ ls -l myscript

-rwxr-xr-x alice alice ! 8o# )7 myscript

Now all #sers have permission to e'ec#te mscript.

To r#n o#r script, we simpl sa

- .Bmscript

 1.$.2 %omments

/omments in a bash script start with a . There sho#ld be a space between the and the firstletter of o#r comment

The first line of the bash script is not reall a comment b#t an indicator on which scriptinglang#age to e'ec#te the script on:

● MBbinBbash tells the *S to #se bash to r#n this script

● MBbinBksh tells the *S to #se another scripting lang#age 6korn shell7 to r#n the script

 1.$.3 'uilt(in &ash scripts

!ost 2NI; based sstems e'tensivel #sed scripts for sstem e'ec#tion. +or e'ample, whenbash first starts on boot #p, it e'ec#tes commands from the script file BetcBprofile. The ?%THvariable among others, is set here.

*n #ser log)in goes to the home director and reads the hidden files .bashprofile, .bashloginand .profile and e'ec#tes those scripts.

Ghen a terminal is started, it e'ec#tes commands from the .bashrc script of the c#rrent #ser.

Ghen a login shell e'its, $ash reads and e'ec#tes commands from the file .bashlogo#t

1.1+ ,dvanced ScriptingIn this section, we will disc#ss how to #sed variables, decision statements and loopingstatements in scripts. Ge will also disc#ss positional inp#t.

1.1).1 *aria&le su&stitution

%s was disc#ssed previo#sl, a bash variable is indicated with a - sign. In realit, the - is acommand that indicates that the val#e of a variable is to be s#bstit#ted at that position whenthe command is r#n.

+or e'ample consider the following commands

$ x=$ echo $x

*perating Sstems 00

Page 12: Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

7/21/2019 Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-3-basic-commands-and-scripting 12/17

J.E.D.I.

*#r variable ' contains the val#e >9. The command echo -' is internall s#bstit#ted as echo>9. %s most of the time we do #se variables in this manner, we onl need to remember thatthe onl time the - does not appear is d#ring variable assignment and when a variable isE;?*"Ted.

This s#bstit#tion can be seen with the newline character. J#st like in most programminglang#ages, a newline can be printed with a backslash n 6i.e. Kn7 However, placing Kn in an echostring does not prod#ce a newline. The wa to do this is to #se a -CKnC. This s#bstit#tes anewline at the position where the backslash n appears

$ echo 2hello Fn world2

hello Fn world

$ echo 2hello2 $2Fn2 2world2

3ello

world

(o# can even #se variables to store the o#tp#t of some programs b encloseing the commandin tick marks O O. +or e'ample, the following script file stores the o#tp#t of ls Betc to a variableand o#tp#ts it.

E4/,in/,ash

x=Gls /etcG

echo CBur #aria,le contains the followin6 filesC

echo $x

 1.1+.1.1 -egular variables

ariables in script files are declared in the #s#al wa. However, the are not visible o#tside ofthe script file #nless the are E;?*"Ted. +or e'ample, o# can view the BetcBprofile script filewhich E;?*"Ts the path variable.

1.1+.1.2 'ositional variables "or user input

Special variables -0, -9 to -L s#bstit#te for arg#ments to the script file. %rg#ments areadditional words separated b spaces in addition to the command that r#ns the script file. Thisis one of the was to have #ser inp#t in a script file. /onsider the following script, which we willsave in a file called argtest. The n#mber of arg#ments passed into the script is represented bthe variable -.

E4/,in/,ash

echo 2y first ar6ument2 $

echo 2y second ar6ument2 $

echo 28um,er of ar6uments passed2 $E

The following wo#ld be the o#tp#ts of argtest on certain arg#ments.

$ ./ar6test

y first ar6ument

y second ar6ument

8um,er of ar6uments passed '

$ ./ar6test hello

y first ar6ument hello

y second ar6ument

8um,er of ar6uments passed

$ ./ar6test hello world star

y first ar6ument hello

y second ar6ument world8um,er of ar6uments passed "

*perating Sstems 09

Page 13: Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

7/21/2019 Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-3-basic-commands-and-scripting 13/17

J.E.D.I.

+or positional variables above -L, the val#e m#st be placed inside brackets 6i.e. -P04Q, -P00Qand so on7.

1.1).2 !ead command (o# can also have inp#t to o#r script file with the read command. +or e'ample, the followingscript file asks for a name

E4/,in/,ash

echo C?nter nameC

read n

echo C3elloHC $n C4C

 1.1).3 "rror %odes

%ll commands in most 2NI; sstems have an error code. Error code val#e ranges from 4 to9@@. $ convention, a program that ret#rns 4 after it e'ec#tes has r#n s#ccessf#ll. %n otherval#e is a false val#e

(o# can find o#t the error code of the last e'ec#ted command in bash via the -5 variable.

+or e'ample, the following script file o#tp#ts the error code of ls after searching a specified file.

E4/,in/,ash

ls $

echo 2he errorcode of ls command is7 2 $I

The following is its sample o#tp#t 6if o# save the file as lstest7

$ ./lstest

<list of files>he errorcode of ls command is7 '

$ ./lstest nosuchfile.txt

8o such file or directory

he errorcode of ls command is7

(o# can specif the error code of o#r script with the e'it command. +or e'ample, at the endof the lstest script, we can ret#rn for o#r error code the error code of ls. Note that we have tosave the val#e of -5 to another variable. Ge do this as -5 ret#rns the error code of the lastcommand r#n. If we did not modif it, it wo#ld ret#rn the error code of echo

E4/,in/,ash

ls $

output=$I

echo 2he errorcode of ls command is7 2 $output

exit $output

 1.1).4 +perators

%rithmetic operators are still the #s#al R, ), 3 or B. The operator ret#rns the remainder ofinteger division.

The res#lt of an arithmetic e'pression can be assigned to a variable #sing the let command.+or e'ample:

$ x=5

$ let Cx = $x J C$ echo $x

*perating Sstems 0A

Page 14: Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

7/21/2019 Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-3-basic-commands-and-scripting 14/17

J.E.D.I.

!

(o# ma also #se the 66 ... 77 command, which eval#ates the e'pression inside the do#bleparenthesis. Note that a - m#st be placed before the 66 for a val#e s#bstit#tion to occ#r.

$ x=$5 J 5LL

$ echo $x'

2nfort#natel, bash does not #nderstand floating)point n#mbers and treats n#mbers with adecimal point as strings.

1.1).5 %onditional Statements

In bash, 4 is for tr#e, 0 is for false. This reflects the val#e ret#rned b all commands in Solaris.$ convention, a program that ret#rns a 4 after it e'ec#tes is a program that r#ns s#ccessf#ll,0 otherwise.

(o# can test for a condition #sing an if)statement. Similar to programing lang#ages, there isthe if statement, the if)else statement and the if)elseif)else statement. The following is thesnta' of the if)elseif)else statement

if M condition N

then

<statements>

elif M condition N

then

<statements>

else

<statements>

fi

The condition part of o#r if statements consist of the following. Note that -a and -b can bevariables or act#al val#es.

● if -a )e1 -b U ) N#merical e1#alit

● if -a V -b U ) String e1#alit

● if -a )ne -b U ) N#merical ine1#alit

● if -a MV -b U ) String ine1#alit

● )gt, )ge, )lt, )le n#merical greater)than, greater)than)e1#al)to, less)than, less)than)

e1#al)to

● )n, )8 not n#ll or n#ll string comparison. +or e'ample, if )n -0 U means if the first

arg#ment is not n#ll.

● if Wcondition0F U XX Wcondition9F U ) and operation

● if Wcondition0F U Wcondition9F U ) or operation

● if M WconditionF U ) not operation. +or e'ample, if M -a )gt -b U means if not a is

greater than b

● )f if the specified filename e'ists. +or e'ample if )f hello.t't U checks if the filehello.t't is valid

● )r, )w, )' checks if the filename has read, write, or e'ec#te privileges respectivel

+or e'ample, recall o#r mscript e'ample. Ge can pass as an arg#ment the filename that wewo#ld like to save the contents of Betc and B#sr to. If no arg#ment was passed, 6i.e. -0 is n#ll7,

*perating Sstems 0>

Page 15: Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

7/21/2019 Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-3-basic-commands-and-scripting 15/17

J.E.D.I.

then we will o#tp#t an error.

E4/,in/,ash

E this is my first ,ash script.

if M -n $ N

then

echo 2istin6 the contents of /etc2 > $ls -l /etc >> $

echo 2istin6 the contents of /usr2 >> $

ls -l /usr >> $

else

echo 2Oou should specify a parameter2

fi

 1.1).6 ,oops

There are two constr#cts for loopsing, the for loop and the while loop.

 1.1+.$.1 or loopThe snta' of the for loop looks like this:

for var in list

do

WstatementsF

done

&ist is a list of val#es var takes on. +or the first pass, var takes on the first element in the list,the second pass, var takes on the second val#e, and so on.

+or e'ample the following for loop lists down the das of the week.

for days in ConC CuesC CPedC ChursC C%riC CatC CunC

do

echo $days

done

 1.1+.$.2 /hile loop

The while loop tests for a condition and keeps on looping while the condition is tr#e. Its snta'is:

while condition U

do

WstatementsF

done

+or e'ample, the following loop prints o#t hello world given a specified arg#ment.

E4/,in/,ash

y='

while M $y -l $ N

do

echo 2hello world2

*perating Sstems 0@

Page 16: Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

7/21/2019 Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-3-basic-commands-and-scripting 16/17

J.E.D.I.

let Cy = y J C

done

 1.11 Basic ,dministration Commands

 1.11.1 Switching to root 

Sstem administration can be done b the s#per #ser or root #ser. +or instance, editing of theconfig#ration files in Betc, s#ch as the profile script file, can onl be done as root. To access theroot acco#nt, o# can log)in as root, or #se the switch #ser command.

$ su

?nter password7 1111111

Note how the prompt has changed to reflect the s#per #ser stat#s. The s# command can alsobe #sed to change to a specified acco#nt.

$ su ,o,

?nter password7 1111111

$ <-- currently lo66ed in as user ,o,L

 1.11.2 #ser administration

The following are some basic commands that the root #ser can #se to administer the sstem

To add #sers in Solaris, o# can #se the #seradd command+or e'ample, the following command adds #ser alice

E useradd -d /export/home/alice -m -s /,in/,ash alice

The additional options are as follows● )d specifies the home director for the #ser. This sho#ld be set#p in Be'portBhome

● )m tells #seradd to man#all create the director

● )s specifies the terminal shell to be #sed b alice, in this case, bash

To change the password of a #ser, o# can r#n the passwd command. +or e'ample, to changethe password of alice r#n:

E passwd alice

If no parameter is given, this changes the password of the c#rrent #ser. This form can also be#sed b non)root #sers to change their passwords.

To delete #sers, o# can r#n the #serdel command. +or e'ample, to delete #ser alice● E userdel -r alice

● )r specifies to remove the #ser director as well

● #seradd W#sernameF ) creates a new #ser with the specified #sername

● #serdel W#sernameF ) deletes a #ser

● passwd W#sernameF ) changes the password of a given #ser. If no parameter is given,

this changes the password of the c#rrent #ser. This form can also be #sed b non)root

*perating Sstems 0=

Page 17: Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

7/21/2019 Teacher's Notes - Lab Chapter 3 - Basic Commands and Scripting

http://slidepdf.com/reader/full/teachers-notes-lab-chapter-3-basic-commands-and-scripting 17/17

J.E.D.I.

#sers to change their passwords.

*perating Sstems 0<