91
Basic Linux Commands Command Example Description cat Sends file contents to standard output. This is a way to list the contents of short files to the screen. It works well with piping. cat .bashrc Sends the contents of the

Basic Linux Commands_ Shell Scripts_debuggingshellscripts

Embed Size (px)

Citation preview

Page 1: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

Basic Linux Commands

Command

Example Description

cat Sends file contents to standard output. This is a way to list the contents of short files to the screen. It works well with piping.

cat .bashrc Sends the contents of the ".bashrc" file to the screen.

cd Change directorycd /home Change the

current working directory to /home. The '/' indicates relative to root, and no

Page 2: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

matter what directory you are in when you execute this command, the directory will be changed to "/home".

cd httpd Change the current working directory to httpd, relative to the current location which is "/home". The full path of the new working directory is "/home/httpd".

cd .. Move to the parent directory of the current directory. This

Page 3: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

command will make the current working directory "/home.

cd ~ Move to the user's home directory which is "/home/username". The '~' indicates the users home directory.

cp Copy filescp myfile yourfile Copy the files

"myfile" to the file "yourfile" in the current working directory. This command will create the file "yourfile" if it

Page 4: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

doesn't exist. It will normally overwrite it without warning if it exists.

cp -i myfile yourfile

With the "-i" option, if the file "yourfile" exists, you will be prompted before it is overwritten.

cp -i /data/myfile . Copy the file "/data/myfile" to the current working directory and name it "myfile". Prompt before overwriting the file.

cp -dpr srcdir destdir

Copy all files from the directory "srcdir"

Page 5: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

to the directory "destdir" preserving links (-p option), file attributes (-p option), and copy recursively (-r option). With these options, a directory and all it contents can be copied to another directory.

dd dd if=/dev/hdb1 of=/backup/

Disk duplicate. The man page says this command is to "Convert and copy a file", but although used by more advanced users, it can be a very handy

Page 6: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

command. The "if" means input file, "of" means output file.

df Show the amount of disk space used on each mounted filesystem.

less

less textfile

Similar to the more command, but the user can page up and down through the file. The example displays the contents of textfile.

ln Creates a symbolic link to a file.

ln -s test symlink Creates a symbolic link

Page 7: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

named symlink that points to the file test Typing "ls -i test symlink" will show the two files are different with different inodes. Typing "ls -l test symlink" will show that symlink points to the file test.

locate A fast database driven file locator.

slocate -u This command builds the slocate database. It will take several minutes to complete this

Page 8: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

command. This command must be used before searching for files, however cron runs this command periodically on most systems.

locate whereis Lists all files whose names contain the string "whereis".

logout Logs the current user off the system.

ls List filesls List files in the

current working directory except those starting with . and only show the file

Page 9: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

name.ls -al List all files in

the current working directory in long listing format showing permissions, ownership, size, and time and date stamp

more Allows file contents or piped output to be sent to the screen one page at a time.

more /etc/profile Lists the contents of the "/etc/profile" file to the screen one page at a time.

ls -al |more Performs a directory listing

Page 10: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

of all files and pipes the output of the listing through more. If the directory listing is longer than a page, it will be listed one page at a time.

mv Move or rename files

mv -i myfile yourfile

Move the file from "myfile" to "yourfile". This effectively changes the name of "myfile" to "yourfile".

mv -i /data/myfile . Move the file from "myfile" from the directory "/data" to the current

Page 11: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

working directory.

pwd Show the name of the current working directory

more /etc/profile Lists the contents of the "/etc/profile" file to the screen one page at a time.

shutdown Shuts the system down.

shutdown -h now Shuts the system down to halt immediately.

shutdown -r now Shuts the system down immediately and the system reboots.

whereis Show where the binary, source

Page 12: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

and manual page files are for a command

whereis ls Locates binaries and manual pages for the ls command.

Editors: emacs, vi, pico, jed, vim

How to write shell script

Following steps are required to write shell script:

(1) Use any editor like vi or mcedit to write shell script.

(2) After writing shell script set execute permission for your script as followssyntax: chmod permission your-script-name

Page 13: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

Examples:$ chmod +x your-script-name$ chmod 755 your-script-name

Note: This will set read write execute(7) permission for owner, for group and other permission is read and execute only(5).

(3) Execute your script assyntax: bash your-script-namesh your-script-name./your-script-name

Examples:$ bash bar$ sh bar$ ./bar

NOTE In the last syntax ./ means current directory, But only . (dot) means execute given command file in current shell without starting the new copy of shell, The syntax for . (dot) command is as follows

Page 14: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

Syntax:. command-name

Example:$ . foo

Now you are ready to write first shell script that will print "Knowledge is Power" on screen. See the common vi command list , if you are new to vi.

$ vi first## My first shell script#clearecho "Knowledge is Power"

After saving the above script, you can run the script as follows:$ ./first

This will not run script since we have not set execute permission for our script first; to do this type command

Page 15: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

$ chmod 755 first$ ./firstFirst screen will be clear, then Knowledge is Power is printed on screen.

Script Command(s) Meaning

$ vi first Start vi editor

## My first shell script#

# followed by any text is considered as comment. Comment gives more information about script, logical explanation about shell script.Syntax:# comment-text

clear clear the screen

echo "Knowledge is To print message or

Page 16: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

Power"

value of variables on screen, we use echo command, general form of echo command is as followssyntax: echo "Message"

How Shell Locates the file (My own bin directory to execute script)

Tip: For shell script file try to give file extension such as .sh, which can be easily identified by you as shell script.

Exercise:1)Write following shell script, save it, execute it and note down the it's output.

$ vi ginfo### Script to print user

Page 17: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

information who currently login , current date & time#clearecho "Hello $USER"echo "Today is \c ";dateecho "Number of user login : \c" ; who | wc -lecho "Calendar"calexit 0

Free

Linux is free. 

First ,It's available free of cost (You don't have to pay to use this OS, other OSes like MS-Windows or Commercial version of Unix may cost you money) 

Page 18: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

Second free means freedom to use Linux, i.e. when you get Linux you will also get source code of Linux, so you can modify OS (Yes OS! Linux OS!!) according to your taste. 

It also offers many Free Software applications, programming languages, and development tools etc. Most of the Program/Software/OS are under GNU General Public License (GPL).

Unix Like 

Unix is almost 35 year old Os. 

In 1964 OS called MULTICS (Multiplexed Information and Computing System) was developed by Bell Labs, MIT & General Electric. But this OS was not the successful one.

Then Ken Thompson (System programmer of Bell Labs) thinks he could do better (In 1991, Linus Torvalds felt he could do better than Minix - History repeats itself.). So Ken

Page 19: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

Thompson wrote OS on PDP - 7 Computer, assembler and few utilities, this is know as Unix (1969). But this version of Unix is not portable. Then Unix was rewrote in C. Because Unix written in 'C', it is portable. It means Unix can run on verity of Hardware platform (1970-71). 

At the same time Unix was started to distribute to Universities. There students and professor started more experiments on Unix. Because of this Unix gain more popularity, also several new features are added to Unix. Then US govt. & military uses Unix for there inter-network (now it is know as INTERNET).

So Unix is Multi-user, Multitasking, Internet-aware Network OS.  Linux almost had same Unix Like feature for e.g.

Like Unix, Linux is also written is C. Like Unix, Linux is also the

Multi-user/Multitasking/32 or 64 bit Network OS.

Page 20: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

Like Unix, Linux is rich in Development/Programming environment.

Like Unix, Linux runs on different hardware platform; for e.g.

o Intel x86 processor (Celeron/PII/PIII/PIV/Old-Pentiums/80386/80486)

o Macintosh PC's 

o Cyrix processor 

o AMD processor 

o Sun Microsystems Sparc processor

o Alpha Processor (Compaq)

Open Source

Linux is developed under the GNU Public License. This is sometimes referred to as a "copyleft", to distinguish it from a copyright.

Page 21: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

Under GPL the source code is available to anyone who wants it, and can be freely modified, developed, and so forth. There are only a few restrictions on the use of the code. If you make changes to the programs , you have to make those changes available to everyone. This basically means you can't take the Linux source code, make a few changes, and then sell your modified version without making the source code available. For more details, please visit the open-source home page.

Common vi editor command list

For this PurposeUse this vi Command

Syntax

To insert new textesc + i ( You have to press 'escape' key then 'i')

To save fileesc + : + w (Press 'escape' key  then 'colon' and finally 'w')

Page 22: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

To save file with file name (save as)

esc + : + w  "filename"

To quit the vi editor esc + : + qTo quit without saving esc + : + q!To save and quit vi editor

esc + : + wq

To search for specified word in forward direction

esc + /word (Press 'escape' key, type /word-to-find, for e.g. to find word 'shri', type as/shri)

To continue with search 

n

To search for specified word in backward direction

esc + ?word (Press 'escape' key, type word-to-find)

To copy the line where cursor is located

esc + yy

To paste the text just deleted or copied at the

esc + p

Page 23: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

cursorTo delete entire line where cursor is located

esc + dd

To delete word from cursor position

esc + dw

To Find all occurrence of given word and Replace then globally without confirmation 

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

For. e.g. :$s/mumbai/pune/gHere word "mumbai" is replace with "pune"

 To Find all occurrence of given word and Replace then globally with confirmation

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

To run shell command like ls, cp or date etc within vi

esc + :!shell-command

For e.g. :!pwd

Page 24: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

How Shell Locates the file

To run script, you need to have in the same directory where you created your script, if you are in different directory your script will not run (because of path settings), For e.g.. Your home directory is ( use $ pwd to see current working directory) /home/vivek. Then you created one script called 'first', after creation of this script you moved to some other directory lets say /home/vivek/Letters/Personal, Now if you try to execute your script it will not run, since script 'first' is in /home/vivek directory, to overcome this problem there are two ways first, specify complete path of your script when ever you want to run it from other directories like giving following command$ /bin/sh   /home/vivek/first

Page 25: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

Now every time you have to give all this detailed as you work in other directory, this take time and you have to remember complete path. 

There is another way, if you notice that all of our programs (in form of executable files) are marked as executable and can be directly executed from prompt from any directory. (To see executables of our normal program give command $ ls -l /bin ) By typing commands like$ bc$ cc myprg.c$ caletc, How its possible? All our executables files are installed in directory called /bin and /bin directory is set in your PATH setting, Now when you type name of any command at $ prompt, what shell do is it first look that command in its internal part (called as internal command, which is part of Shell itself, and always available to execute), if found as internal

Page 26: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

command shell will execute it, If not found It will look for current directory, if found shell will execute command from current directory, if not found, then Shell will Look PATH setting, and try to find our requested commands executable file in all of the directories mentioned in PATH settings, if found it will execute it, otherwise it will give message "bash: xxxx :command not found", Still there is one question remain can I run my shell script same as these executables?, Yes you can, for this purpose create bin directory in your home directory and then copy your tested version of shell script to this bin directory. After this you can run you script as executable file without using command like$ /bin/sh   /home/vivek/first Command to create you own bin directory.

$ cd$ mkdir bin$ cp first ~/bin$ firstEach of above commands can be explained as follows:

Page 27: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

Each of above command

Explanation

$ cdGo to your home directory

$ mkdir bin

Now created bin directory, to install your own shell script, so that script can be run as independent program or can be accessed from any directory

$ cp   first ~/bincopy your script 'first' to your bin directory

$ firstTest whether script is running or not (It will run)

Answer to Variable sections exercise

Page 28: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

Q.1.How to Define variable x with value 10 and print it on screen.$ x=10$ echo $x

Q.2.How to Define variable xn with value Rani and print it on screenFor Ans. Click here$ xn=Rani$ echo $xn

Q.3.How to print sum of two numbers, let's say 6 and 3$ echo 6 + 3This will print 6 + 3, not the sum 9, To do sum or math operations in shell use expr, syntax is as follows  Syntax: expr   op1   operator   op2Where, op1 and op2 are any Integer Number (Number without decimal point) and operator can be+ Addition- Subtraction

Page 29: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

/ Division% Modular, to find remainder For e.g. 20 / 3 = 6 , to find remainder 20 % 3 = 2, (Remember its integer calculation)\* Multiplication$ expr 6 + 3 Now It will print sum as 9 , But$ expr 6+3will not work because space is required between number and operator (See Shell Arithmetic)

Q.4.How to define two variable x=20, y=5 and then to print division of x and y (i.e. x/y)For Ans. Click here$x=20$ y=5$ expr x / y

Q.5.Modify above and store division of x and y to variable called zFor Ans. Click here$ x=20$ y=5

Page 30: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

$ z=`expr x / y`$ echo $z Q.6.Point out error if any in following script

$ vi   variscript### Script to test MY knolwdge about variables!#myname=Vivekmyos   =  TroubleOS    -----> ERROR 1myno=5echo "My name is $myname"echo "My os is $myos"echo "My number is   myno,   can you see this number"  ----> ERROR 2

Following script should work now, after bug fix!

$ vi   variscript### Script to test MY knolwdge about

Page 31: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

variables!#myname=Vivekmyos=TroubleOSmyno=5echo "My name is $myname"echo "My os is $myos"echo "My number is   $myno,   can you see this number"

Parameter substitution.

Now consider following command$($ echo 'expr 6 + 3')

The command ($ echo 'expr 6 + 3')  is know as Parameter substitution. When a command is enclosed in backquotes, the command get executed and we will get output. Mostly this is used in conjunction with other commands. For e.g.

$pwd$cp /mnt/cdrom/lsoft/samba*.rmp `pwd`

Now suppose we are working in directory called "/home/vivek/soft/artical/linux/lsst" and I want

Page 32: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

to copy some samba files from "/mnt/cdrom/lsoft" to my current working directory, then my command will be something like

$cp   /mnt/cdrom/lsoft/samba*.rmp    /home/vivek/soft/artical/linux/lsst

Instead of giving above command I can give command as follows

$cp  /mnt/cdrom/lsoft/samba*.rmp  `pwd`

Here file is copied to your working directory. See the last Parameter substitution of `pwd` command, expand it self to /home/vivek/soft/artical/linux/lsst. This will save my time.$cp  /mnt/cdrom/lsoft/samba*.rmp  `pwd`

Future Point: What is difference between following two command?$cp  /mnt/cdrom/lsoft/samba*.rmp  `pwd`

Page 33: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

                        A N D

$cp  /mnt/cdrom/lsoft/samba*.rmp  .

Try to note down output of following Parameter substitution.

$echo "Today date is `date`"$cal > menuchoice.temp.$$$dialog --backtitle "Linux Shell Tutorial"  --title "Calender"  --infobox  "`cat  menuchoice.temp.$$`"  9 25 ; read

Answer to if command. 

A) There is file called foo, on your disk and you give command, $ ./trmfi   foo what will be output.

B) If bar file not present on your disk and you give command, $ ./trmfi   bar what will be output.

Page 34: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

C) And if you type $ ./trmfi, What will be output.

Answer to Variables in Linux.

1) If you want to print your home directory location then you give command:     (a) $ echo $HOME

                    or

     (b) $ echo HOME

Which of the above command is correct & why?

Ans.: (a) command is correct, since we have to print the contains of variable (HOME) and not the HOME. You must use $ followed by variable name to print variables cotaines.

Answer to Process Section.

Page 35: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

1) Is it example of Multitasking?Ans.: Yes, since you are running two process simultaneously.

2) How you will you find out the both running process (MP3 Playing & Letter typing)?Ans.: Try $ ps aux or $ ps ax | grep  process-you-want-to-search

3) "Currently only two Process are running in your Linux/PC environment", Is it True or False?, And how you will verify this?Ans.: No its not true, when you start Linux Os, various process start in background for different purpose. To verify this simply use top or ps aux command.

4) You don't want to listen music (MP3 Files) but want to continue with other work on PC, you will take any of the following action:

1. Turn off Speakers 2. Turn off Computer / Shutdown

Linux Os

3. Kill the MP3 playing process

Page 36: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

4. None of the above

Ans.: Use action no. 3 i.e. kill the MP3 process.Tip: First find the PID of MP3 playing process by issuing command:$ ps ax | grep mp3-process-name Then in the first column you will get PID of process. Kill this PID to end the process as:$ kill  PID

Or you can try killall command to kill process by name as follows:$ killall  mp3-process-name

Linux Console (Screen) 

How can I write colorful message on Linux Console? , mostly this kind of question is asked by newcomers (Specially those who are learning shell programming!). As you know in Linux everything is considered as a file, our console is one of such special file. You can write special character sequences to console, which control

Page 37: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

every aspects of the console like Colors on screen, Bold or Blinking text effects, clearing the screen, showing text boxes etc. For this purpose we have to use special code called escape sequence code.  Our Linux console is based on the DEC VT100 serial terminals which support ANSI escape sequence code.

What is special character sequence and how to write it to Console?

By default what ever you send to console it is printed as its. For e.g. consider following echo statement,$ echo "Hello World"Hello WorldAbove echo statement prints sequence of character on screen, but if there is any special escape sequence (control character) in sequence , then first some action is taken according to escape sequence (or control character) and then normal character is printed on console. For e.g. following echo command prints message in Blue color on console

Page 38: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

$ echo -e "\033[34m   Hello Colorful  World!"Hello Colorful  World!

Above echo statement uses ANSI escape sequence (\033[34m), above entire string ( i.e.  "\033[34m   Hello Colorful  World!" ) is process as follows

1) First \033, is escape character, which causes to take some action2) Here it set screen foreground color to Blue using [34m escape code.3) Then it prints our normal message Hello Colorful  World! in blue color.

Note that ANSI escape sequence begins with \033 (Octal value) which is represented as ^[ in termcap and terminfo files of terminals and documentation.

You can use echo statement to print message, to use ANSI escape sequence you must use -e option (switch) with echo statement, general

Page 39: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

syntax is as followsSyntaxecho   -e  "\033[escape-code    your-message"

In above syntax you have to use\033[ as its with different escape-code for different operations. As soon as console receives the message it start to process/read it, and if it found escape character (\033) it moves to escape mode, then it read "[" character and moves into Command Sequence Introduction (CSI) mode. In CSI mode console reads a series of ASCII-coded decimal numbers (know as parameter) which are separated by semicolon (;) . This numbers are read until console action letter or character is not found (which determines what action to take). In above example

\033Escape

character[ Start of CSI34 34 is parameter

mm is letter (specifies action)

Page 40: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

Following table show important list of such escape-code/action letter or character

Character or letter

Use in CSI Examples

hSet the ANSI mode

echo -e "\033[h"

lClears the ANSI mode

echo -e "\033[l"

m

Useful to show characters in different colors or effects such as BOLD and Blink, see below for parameter taken by m.

echo -e  "\033[35m Hello World"

q

Turns keyboard num lock, caps lock, scroll lock LED on or off, see below.

echo -e "\033[2q"

Page 41: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

s

Stores the current cursor x,y position (col , row position) and attributes

echo -e "\033[7s"

uRestores cursor position and attributes

echo -e "\033[8u"

m understand following parameters

Parameter Meaning Example

0

Sets default color scheme (White foreground and Black background), normal intensity, no blinking etc.

 

1 Set BOLD intensity

$ echo -e "I am \033[1m BOLD \033[0m Person"I am BOLD

Page 42: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

PersonPrints BOLD word in bold intensity and next ANSI Sequence remove bold effect (\033[0m)

2 Set dim intensity

$ echo -e "\033[1m  BOLD \033[2m DIM  \033[0m"

5 Blink Effect$ echo -e "\033[5m Flash!  \033[0m"

7

Reverse video effect i.e. Black foreground and white background in default color scheme

$ echo -e "\033[7m Linux OS! Best OS!! \033[0m"

11 Shows special control character

$ press alt + 178$ echo -e "\

Page 43: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

as graphics character. For e.g. Before issuing this command press alt key (hold down it) from numeric key pad press 178 and leave both key; nothing will be printed. Now give --> command shown in example and try the above, it works. (Hey you must know extended ASCII Character for this!!!)

033[11m"$ press alt + 178$ echo -e "\033[0m"$ press alt + 178

25Removes/disables blink effect

 

Page 44: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

27Removes/disables reverse effect

 

30 - 37

Set foreground color31 - RED32 - Greenxx - Try to find yourself this left as exercise for you :-)

$ echo -e "\033[31m I am in Red"

40 - 47

Set background colorxx - Try to find yourself this left as exercise for you :-)

$ echo -e "\033[44m Wow!!!"

q understand following parameters

Parameters Meaning

0Turns off all LEDs on Keyboard

1 Scroll lock LED on and

Page 45: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

others off

2Num lock LED on and others off

3Caps lock LED on and others off

This is just quick introduction about Linux Console and what you can do using this Escape sequence. Above table does not contains entire CSI sequences. My up-coming tutorial series on C Programming Language will defiantly have entire story with S-Lang and curses (?). What ever knowledge you gain here will defiantly first step towards the serious programming using c. This much knowledge is sufficient for  Shell Programming, now try the following exercise :-) I am Hungry give me More Programming Exercise & challenges! :-)

1) Write function box(),  that will draw box on screen (In shell Script)    box (left, top, height, width)

Page 46: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

    For e.g. box (20,5,7,40)   

   

Hint: Use ANSI Escape sequence1) Use of 11 parameter to m2) Use following for cursor movement   row;col H      or   rowl;col f    For e.g.  $ echo   -e "\033[5;10H Hello"  $ echo   -e "\033[6;10f Hi"

Page 47: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

In Above example prints Hello message at row 5 and column 6 and Hi at 6th row and 10th Column.

Shell Built in Variables

Shell Built in

VariablesMeaning

$#

Number of command line arguments. Useful to test no. of command line args in shell script.

$* All arguments to shell$@ Same as above$- Option supplied to shell$$ PID of shell

$!PID of last started background process (started with &)

Page 48: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

How Does Shell Script Looping Work?Shell scripts written in Bash can implement looping, or iteration, with the while, until, and for constructs. In each case, a block of code is executed repeatedly until a loop exit condition is satisfied. The script then continues on from that point.

The while Statement

In a while loop, the block of code between the do and done statements is executed so long as the conditional expression is true. Think of it as saying, "Execute while this condition remains true." Here's an example:

while [ "$*" != "" ]do  echo "Argument value is: $1"  shiftdone

Page 49: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

This trivial example prints the value of each argument passed to the shell script. Translated to English, the while condition says to continue so long as the input argument string is not null. You could also code the while statement as

while [ -n "$*" ]

but I think the first method is much easier to read and understand.

You might think that this loop would continue to print the first argument ($1) forever and ever, since you don't expect the value of the $* variable (the list of arguments from the command line) to change during the course of running the script. You'd be right, except that I slipped the shift command into the body of the loop.

What shift does is discard the first argument and reassign all the $n variables--so the new $1 variable gets the

Page 50: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

value that used to be in $2, and so on. Accordingly, the value in $* gets shorter and shorter each time through the loop, and when it finally becomes null, the loop is done.

The until Statement

The until construct works almost exactly the same as while. The only difference is that until executes the body of the loop so long as the conditional expression is false, whereas while executes the body of the loop so long as the conditional expression is true. Think of it as saying, "Execute until this condition becomes true."

Let's code the previous example using an until loop this time and making it a little fancier by adding a counter variable:

count=1until [ "$*" = "" ]do  echo "Argument number

Page 51: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

$count : $1 "  shift  count=`expr $count + 1`done

Again, you could have coded the until statement as

until [ -z "$*" ]

but I recommend not using the -n and -z operators because it's harder to remember what they do.

The only new concept here is the strange-looking line that increments the counter:

count=`expr $count + 1`

The expr command signals to the shell that we're about to perform a mathematical calculation instead of a string operation. And the doodads that look kind of like single quotation marks are not--they're the backtick (`) character, found to the left of the number 1 key on most keyboards. By

Page 52: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

enclosing an expression in backticks, you tell the shell to assign the result of a Linux command to a variable, instead of printing it to the screen.

Note: The spaces on either side of the plus sign are required.

The for Statement

The for statement is yet another way to implement a loop in a shell script. The general form of the for construct is shown here:

for item in listdo  something useful with $itemdone

Each time through the loop, the value of the item variable is assigned to the nth item in the list. When you've processed all the items in the list, the loop is done. Here's an

Page 53: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

example similar to the until and while loops you saw earlier in this section:

for item in "$*"do  echo "Argument value is: $item"done

Can I Debug a Shell Script?Debugging Shell Scripts

Sometimes shell scripts just don't work the way you think they should, or you get strange error messages when running your script. Just remember: The computer is always right. It's easy to omit a significant blank, quotation mark, or bracket, or to mistakenly use a single quotation mark when you should have used double quotation marks or a backtick.

Page 54: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

When you get unexpected behavior from a shell script and you're thinking "I just know this is coded right . . . the computer is wrong!"--remember: The computer is always right. But fortunately, there is help. By prefixing your shell invocation with bash -x, you can turn on tracing to see what's really happening. Let's say we have the following listarg script:

count=1until [ "$*" = "" ]doecho "Arg $count : $1 "shiftcount=$count+1done

At first glance, it looks golden, but for some reason the counter is not incrementing properly. Try running it with the command

% bash -x listarg abc def

Page 55: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

and look at the trace output as the shell executes. The lines prefixed with a plus sign show the progress of the running script, and the lines without the plus sign are the script's normal output.

+ count=1+ [ abc def = ]+ echo Arg 1 : abcArg 1 : abc+ shift+ count=1+1 Hmmm . . .+ [ def = ]+ echo Arg 1+1 : defArg 1+1 : def Not Good!+ shift+ count=1+1+1+ [ = ]

Instead of printing Arg 2 : def, we got Arg 1+1 : def. But the trace output line reading count=1+1 nails the problem. You forgot to use the expr command, so the shell is

Page 56: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

treating this as a string concatenate instead of a mathematical calculation.

Note: You can always press Ctrl-C to stop a running shell script. This is handy if you accidentally create a script with an infinite loop (one that will never end by itself).

Ubuntu Linux Shell Commands quick reference

The following is a quick reference list of some useful Ubuntu shell commands along with a short description of common usage. There are more, but this basic list was created to help familiarize the newly introduced Ubuntu user who might be migrating from a Windows operating environment.

*Ubuntu is a product of Canonical Ltd

cd – change directory

usage: cd <directory name>

Page 57: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

clear – clear screen

cp - copy files (similar to copy in DOS)

cp <filename> < new location>

diff – compare files

diff <file1> <file2>

exit – exit or quit

find – find files

find -name <filename>

fsck – check disk integrity (similar to DOS scandisk)

ifconfig – view network settings (similar to DOS ipconfig)

less – view text files

less <filename>

lpr – print text files

lpr <filename>

Page 58: Basic Linux Commands_ Shell Scripts_debuggingshellscripts

man – get help

man <command>

mkdir – create a directory

mkdir <directory name>

mv – move or rename files

mv <filename> <new location>

ping – check a network connection

ping <address>

rm – delete or remove a directory or file (similar to del in DOS)

rm -rf <directoryname>

rm <filename>

tracepath – view a network route

tracepath <address>

vi – edit text files

vi <filename>

Page 59: Basic Linux Commands_ Shell Scripts_debuggingshellscripts