Linux Script
Linux Script
click
on the Exceed icon and then use putty to connect to the server kiwi. Enter your
login (user name) and password at relevant prompts.
2. Enter these commands at the UNIX prompt, and try to interpret the output. Ask
questions and don't be afraid to experiment (as a normal user you cannot do much
harm):
o echo hello world
o passwd
o date
o hostname
o arch
o uname -a
o dmesg | more (you may need to press q to quit)
o uptime
o who am i
o who
o id
o last
o finger
o w
o top (you may need to press q to quit)
o echo $SHELL
o echo {con,pre}{sent,fer}{s,ed}
o man "automatic door"
o man ls (you may need to press q to quit)
o man who (you may need to press q to quit)
o who can tell me why i got divorced
o lost
o clear
o cal 2000
o cal 9 1752 (do you notice anything unusual?)
o bc -l (type quit or press Ctrl-d to quit)
o echo 5+4 | bc -l
o yes please (you may need to press Ctrl-c to quit)
o time sleep 5
o history
25. Experiment with the options on the ls command. What do the d, i, R and F options do?
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
17. Type mount (with no parameters) and try to interpret the output.
////////////////////////////////////////////////////////////////////////////////////////////////////////////
1. Archive the contents of your home directory using tar. Compress the tar file with
gzip. Now uncompress and unarchive the .tar.gz file using cat, tar and gzip on
one command line.
2. Use find to compile a list of all directories in the system, redirecting the output so
that the list of directories ends up in a file called directories.txt and the list of
error messages ends up in a file called errors.txt.
3. Try the command sleep 5. What does this command do?
4. Run the command in the background using &.
5. Run sleep 15 in the foreground, suspend it with Ctrl-z and then put it into the
background with bg. Type jobs. Type ps. Bring the job back into the foreground
with fg.
6. Run sleep 15 in the background using &, and then use kill to terminate the
process by its job number. Repeat, except this time kill the process by specifying
its PID.
7. Run sleep 15 in the background using &, and then use kill to suspend the
process. Use bg to continue running the process.
8. Startup a number of sleep 60 processes in the background, and terminate them all
at the same time using the pkill command.
9. Use ps, w and top to show all processes that are executing.
10. Use ps -aeH to display the process hierarchy. Look for the init process. See if
you can identify important system daemons. Can you also identify your shell and
its subprocesses?
11. Combine ps -fae with grep to show all processes that you are executing, with the
exception of the ps -fae and grep commands.
12. Start a sleep 300 process running in the background. Log off the server, and log
back in again. List all the processes that you are running. What happened to your
sleep process? Now repeat, except this time start by running nohup sleep 300.
13. Multiple jobs can be issued from the same command line using the operators ;, &&
and ||. Try combining the commands cat nonexistent and echo hello using each
of these operators. Reverse the order of the commands and try again. What are the
rules about when the commands will be executed?
14. What does the xargs command do? Can you combine it with find and grep to find
yet another way of searching all files in the /home subdirectory tree for the word
hello?
15. What does the cut command do? Can you use it together with w to produce a list
of login names and CPU times corresponding to each active process? Can you
now (all on the same command line) use sort and head or tail to find the user
whose process is using the most CPU?
///////////////////////////////////////////////////////////////////////////////////////////////////////////
1. Use telnet to request a web page from the web server www.doc.ic.ac.uk by
connecting to port 80, as shown in the notes.
2. Use ping to find the round-trip delay to www.altavista.com.
3. Use traceroute to see the network route taken to www.altavista.com (which is in
the USA). Can you tell which cities your network traffic passes through?
4. Use ftp to connect to the FTP site sunsite.doc.ic.ac.uk. Obtain the latest
version of the package units (in the form of a .tar.gz file) from the directory
packages/gnu/units. Decompress and unarchive the .tar.gz file. Type configure
and then make. Run the executable program that is produced as " ./units -f
units.dat". What does the program do? If you were the system administrator,
what would you have to do to install the package for everyone to use?
5. Use wget to get a copy of the web page http://www.doc.ic.ac.uk/index.html.
Have a look at the contents of the file. Can you use sed to strip out the
HTML tags (text enclosed in < and >) to leave you with just plain text?
6. Use finger or who to get a list of users on the machine.
7. Use write to send them a message. To stop people from sending you messages,
type "mesg n". To reenable messages, type "mesg y".
8. Try use talk to send a message to someone (N.B. this may not work).
9. List all your processes, using sed to substitute "me" for your username.
10. Use who, awk, sort and uniq to print out a sorted list of the logins of active users.
11. Use awk on /etc/passwd to produce a list of users and their login shells.
12. Write an awk script that prints out all lines in a file except for the first two.
13.Modify the awk script in the notes so that it doesn't increase the number of
players used to calculate the average if the manner of dismissal is "not-out".
14. Create a file called hello.c containing the simple "hello world" program in the
notes. Create an appropriate makefile for compiling it. Run make.
15. Use man -k to find a suitable utility for viewing postscript files.
////////////////////////////////////////////////////////////////////////////////////////////////////////
1. Copy the file mole.txt into your home directory (press shift and the left mouse
button to download the file using Netscape).
2. Edit your copy of the document using vi.
3. Go to the end of the document and type in the following paragraph:
Joined the library. Got Care of the Skin, Origin of the Species, and a
book by a woman my mother is always going on about. It is called Pride and
Prejudice, by a woman called Jane Austen. I could tell the librarian was
impressed. Perhaps she is an intellectual like me. She didn't look at my
spot, so perhaps it is getting smaller.
4. Correct the three spelling errors in the first three lines of the first paragraph (one
error per line) and remove the extra "Geography" in the 3rd line of the first
paragraph.
5. Add the words "About time!" to the end of the second paragraph.
6. Delete the sentence "Time flies like an arrow but fruit flies like a
banana" and re-form the paragraph.
7. Replace all occurrences of "is" with "was".
8. Swap the two paragraphs.
9. Save the file and quit.
10. Repeat the exercise with emacs. Which did you find easier?
11. Can you write a simple C program (say the hello world program) and makefile,
compile and run it - all from inside emacs?
12. If you'd like an indepth vi tutorial try running "vimtutor". For an indepth emacs
tutorial, type M-x help-with-tutorial from inside emacs.
/////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
N.B. Please perform these tasks on your home PC and take extra care when using the root
account. Since your commands will be carried out without the safeguards that apply to ordinary
users, you may do serious damage to the system. If in doubt, please ask (preferably before
pressing !)
8. Switch back to being root. Add a line to /etc/inittab which will ensure that your
mini web-server will respawn itself if it dies. Kill your web server (using kill)
and see if the respawning works (init re-examines the /etc/inittab file
whenever one of its descendant processes dies so you should not have long to wait
for this to take effect). It may be helpful to monitor the system messages file with
tail -f /var/log/messages.
//////////////////////////////////////////////////////////////////////////////////////
1. Use your favourite UNIX editor to create the simple shell script given in Section
8.4 of the notes. Run it, and see how the contents of the script relates to the
output.
2. Extend the script so that it generates a random secret number between 1 and 100
(c.f. Exercise Sheet 3, Question 16) and then keeps asking the user to guess the
secret number until they guess correctly. The script should give the user hints
such as "I'm sorry your guess is too low" or "I'm sorry your guess is too high".
3. Write a shell script which renames all .txt files as .text files. The command
basename might help you here.
4. Write a shell script called pidof which takes a name as parameter and returns the
PID(s) of processes with that name.
5. Shell scripts can also include functions. Functions are declared as:
function funcname() {
statements
}
6. Modify your .bash_profile script so that your PATH includes the current directory
(.) and so that your environment variable EDITOR is set to emacs or vi (or whatever
else you prefer to use). Run the modified script using source .bash_profile and
check that the changes you made have been applied to the current shell (type set).
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
Introduction to UNIX:
Lecture Eight
8.1 Objectives
This chapter covers:
There are many different shells available on UNIX systems (e.g. sh, bash, csh, ksh, tcsh etc.),
and they each support a different command language. Here we will discuss the command
language for the Bourne shell sh since it is available on almost all UNIX systems (and is also
supported under bash and ksh).
$ bob='hello world'
$ echo $bob
hello world
$
Variables created within a shell are local to that shell, so only that shell can access them. The
set command will show you a list of all variables currently defined in a shell. If you wish a
variable to be accessible to commands outside the shell, you can export it into the environment:
$ export bob
(under csh you used setenv). The environment is the set of variables that are made available to
commands (including shells) when they are executed. UNIX commands and programs can read
the values of environment variables, and adjust their behaviour accordingly. For example, the
environment variable PAGER is used by the man command (and others) to see what command
should be used to display multiple pages. If you say:
$ export PAGER=cat
and then try the man command (say man pwd), the page will go flying past without stopping. If
you now say:
$ export PAGER=more
normal service should be resumed (since now more will be used to display the pages one at a
time). Another environment variable that is commonly used is the EDITOR variable which
specifies the default editor to use (so you can set this to vi or emacs or which ever other editor
you prefer). To find out which environment variables are used by a particular command,
consult the man pages for that command.
Another interesting environment variable is PS1, the main shell prompt string which you can
use to create your own custom prompt. For example:
The shell often incorporates efficient mechanisms for specifying common parts of the shell
prompt (e.g. in bash you can use \h for the current host, \w for the current working directory, \d
for the date, \t for the time, \u for the current user and so on - see the bash man page).
Another important environment variable is PATH. PATH is a list of directories that the shell uses
to locate executable files for commands. So if the PATH is set to:
/bin:/usr/bin:/usr/local/bin:.
and you typed ls, the shell would look for /bin/ls, /usr/bin/ls etc. Note that the PATH
contains'.', i.e. the current working directory. This allows you to create a shell script or
program and run it as a command from your current directory without having to explicitly say
"./filename".
Note that PATH has nothing to with filenames that are specified as arguments to commands (e.g.
cat myfile.txt would only look for ./myfile.txt, not for /bin/myfile.txt,
/usr/bin/myfile.txt etc.)
#!/bin/sh
# this is a comment
echo "The number of arguments is $#"
echo "The arguments are $*"
echo "The first is $1"
echo "My process number is $$"
echo "Enter a number from the keyboard: "
read number
echo "The number you entered was $number"
The shell script begins with the line " #!/bin/sh" . Usually "#" denotes the start of a comment,
but #! is a special combination that tells UNIX to use the Bourne shell ( sh) to interpret this
script. The #! must be the first two characters of the script. The arguments passed to the script
can be accessed through $1, $2, $3 etc. $* stands for all the arguments, and $# for the number of
arguments. The process number of the shell executing the script is given by $$. the read
number statement assigns keyboard input to the variable number.
To execute this script, we first have to make the file simple executable:
$ ls -l simple
-rw-r--r-- 1 will finance 175 Dec 13 simple
$ chmod +x simple
$ ls -l simple
-rwxr-xr-x 1 will finance 175 Dec 13 simple
$ ./simple hello world
The number of arguments is 2
The arguments are hello world
The first is hello
My process number is 2669
Enter a number from the keyboard:
5
The number you entered was 5
$
We can use input and output redirection in the normal way with scripts, so:
$ echo 5 | simple hello world
would produce similar output but would not pause to read a number from the keyboard.
if [test ]
then
commands-if-test-is-true
else
commands-if-test-is-false
fi
The test condition may involve file characteristics or simple string or numerical
comparisons. The [ used here is actually the name of a command ( /bin/[) which
performs the evaluation of the test condition. Therefore there must be spaces
before and after it as well as before the closing bracket. Some common test
conditions are:
-s file
true if file exists and is not empty
-f file
true if file is an ordinary file
-d file
true if file is a directory
-r file
true if file is readable
-w file
true if file is writable
-x file
true if file is executable
$X -eq $Y
true if X equals Y
$X -ne $Y
true if X not equal to Y
$X -lt $Y
true if X less than $Y
$X -gt $Y
true if X greater than $Y
$X -le $Y
true if X less than or equal to Y
$X -ge $Y
true if X greater than or equal to Y
"$A" = "$B"
true if string A equals string B
"$A" != "$B"
true if string A not equal to string B
$X ! -gt $Y
true if string X is not greater than Y
$E -a $F
true if expressions E and F are both true
$E -o $F
true if either expression E or expression F is true
• for loops
The following script sorts each text files in the current directory :
#!/bin/sh
for f in *.txt
do
echo sorting file $f
cat $f | sort > $f.sorted
echo sorted file has been output to $f.sorted
done
• while loops
while [ test ]
do
statements (to be executed while test is true)
done
The following script waits until a non-empty file input.txt has been created:
#!/bin/sh
while [ ! -s input.txt ]
do
echo waiting...
sleep 5
done
echo input.txt is ready
You can abort a shell script at any point using the exit statement, so the following
script is equivalent:
#!/bin/sh
while true
do
if [ -s input.txt ]
echo input.txt is ready
exit
fi
echo waiting...
sleep 5
done
• case statements
case statements are a convenient way to perform multiway branches where one
input pattern must be compared to several alternatives:
casevariable in
pattern1)
statement (executed if variable matches pattern1)
;;
pattern2)
statement
;;
etc.
esac
The following script uses a case statement to have a guess at the type of non-
directory non-executable files passed as arguments on the basis of their extensions
(note how the "or" operator | can be used to denote multiple patterns, how " *" has
been used as a catch-all, and the effect of the forward single quotes `):
#!/bin/sh
for f in $*
do
if [ -f $f -a ! -x $f ]
then
case $f in
core)
echo "$f: a core dump file"
;;
*.c)
echo "$f: a C program"
;;
*.cpp|*.cc|*.cxx)
echo "$f: a C++ program"
;;
*.txt)
echo "$f: a text file"
;;
*.pl)
echo "$f: a PERL script"
;;
*.html|*.htm)
echo "$f: a web document"
;;
*)
echo "$f: appears to be "`file -b $f`
;;
esac
fi
done
Any UNIX command or program can be executed from a shell script just as if you
would on the line command line. You can also capture the output of a command
and assign it to a variable by using the forward single quotes ` `:
#!\bin\sh
lines=`wc -l $1`
echo "the file $1 has $lines lines"
This script outputs the number of lines in the file passed as the first parameter.
• arithmetic operations
The Bourne shell doesn't have any built-in ability to evaluate simple mathematical
expressions. Fortunately the UNIX expr command is available to do this. It is
frequently used in shell scripts with forward single quotes to update the value of a
variable. For example:
export PATH=$PATH:~/bin
in your .profile. If you subsequently modify your .profile and you wish to import the
changes into your current shell, type:
$ source .profile
or
$ . ./profile
The source command is built into the shell. It ensures that changes to the environment made in
.profile affect the current shell, and not the shell that would otherwise be created to execute
the .profile script.
With csh, to add the directory ~/bin to your PATH, you can include the line:
in your .cshrc.