71
LPI Linux LPIC1 Module 5

LPI Linux LPIC1 - Politechnika Opolskapelc.we.po.opole.pl/LinuxShortCourse/LPI Linux LPIC1 - Module 5.pdf · Module Contents • 1 Evans Ikua Lead Editor Kenya [email protected]

  • Upload
    lelien

  • View
    234

  • Download
    1

Embed Size (px)

Citation preview

LPI Linux LPIC1

Module 5

Module Contents

• 1 Evans Ikua Lead Editor Kenya [email protected] • 2 Chris Brown Content Author UK [email protected] • 3 Mark Clarke Content Author RSA [email protected] • 4 Brian Ssennoga Content Author Uganda [email protected] • 5 Trust Zifa Material co-editor Zimbabwe [email protected] • 6 John Matogo Material co-editor Kenya john [email protected] • 7 Ken Mutua Material co-editor Kenya [email protected] • 8 Bernard Owuor Material co-editor Kenya [email protected] • 9 Sisay Adugna Material co-editor Ethiopia [email protected] • 10 Balthas Seibold Senior Project • Manager - GIZ • Germany [email protected] • 11 Petra Hagemann Project Manager - GIZ Germany [email protected] • 12 George Nyambuya Africa Coordinator - • ict@innovation • RSA [email protected] • 13 David Paulus Intern - GIZ Germany [email protected]

Module Contents

Shell Scripting and Data Management • Set environment variables (e.g. PATH) at login or

when spawning a new shell.

• Write BASH functions for frequently used sequences of commands.

• Maintain skeleton directories for new user accounts.

• Set command search path with the proper directory.

Module Contents

Shell commands • ls - This command 'lists' the contents of your

present working directory.

• pwd - Shows you what your present working directory is.

• cd - Lets you change directories.

• rm - removes one or more files.

• rmdir - Remove an empty directory.

• mkdir - Make a directory.

Module Contents

Shell commands • ps - Provides a list of currently running processes. • cp - Copy a file. • mv - Move a file (this is also used to rename a file,

"moving" it from one file name to another.) • grep - The global regular expression print program lets

you search through a file or output of another program.

• find - Find a file on the filesystem • man - Displays the manual for most commands

(including 'man').

Module Contents

Login vs. Non-login shell • Login shell: Shell started with login, bash -l or su

command • Non-login shell: Shell started any other way

Reason for 2 types of shell • The login shell reads a series of configuration file as it

is started. • The non-login shells inherit settings (environment

variables) from the parent program which started it.

Module Contents

Variable inheritance Variables declared inside a shell are inherited by child processes if the variable has been exported. If a child process changes its own copy of an exported variable, the parent shell's copy is not changed. The changed value is exported to any sub-child processes. All exported shell variables keep their export settings in the child process. If a shell script is called from within a shell a new child non-login shell is started. If a shell script is started with the '.' command within a shell, then the script is run within that current shell.

Module Contents

Interactive and non-interactive shells • Interactive shell: Provides a prompt where the user

can type commands.

• Non-Interactive shell: No shell prompt – started by calling a shell script or by the command:

# sh -c 'command...'

• Sequence of events when bash starts

Module Contents

Interactive and non-interactive shells Interactive-login bash • bash --login or su - username or from login • /etc/profile Executed first from interactive login shell. It

contains system-wide • environment settings. • ~/.bash_profile Individual user's shell settings. • ~/.bash_login Executed if ~/.bash_profile doesn't exist. • ~/.profile Executed if ~/.bash_login or ~/.bash_profile

doesn't exist.

Module Contents

Interactive and non-interactive shells Interactive non-login bash

• su username or bash -c command

• ~/.bashrc The only script executed when started. Inherits from

Non-Interactive non-login bash (forked when scripts are run)

• The above scripts are not executed but inherit environment from their parent.

• BASH_ENV Reads file in the variable BASH_ENV.

• ENV Reads file in the variable ENV if BASH_ENV doesn't exist. parent bash environment.

Module Contents

Interactive and non-interactive shells Extra files

• /etc/inputrc - System bash line editing (readline) configuration file

• ~/.inputrc - Individual bash line editing (readline) configuration file

• ~/.bash_logout - Executed (if exists) when a login shell exits.

Module Contents

Commands for shell/environment variables • Variablename=Value - Assigns a value to a set (existing) or

non-set variable. • export Variablename or

declare -x Variablename - Sets the export tag ON for an existing shell var.

• export Variablename=value or declare -x Variablename=value - Assign a value to a set (existing) or non-set variable and sets its export tag ON, all in one command.

• env - Displays all the environment variables (export tag ON) • export - Same as env command except the display format is

different eg. declare -x PAGER="less"

Module Contents

Aliases • Aliases are normally used to create command shortcuts (short names). • Aliases are NOT exportable: not passed-on to sub-shells or child process. • Aliases are not recognized in scripts. • An alias can call another alias within a command. • Example alias li="ls -l"; alias al="li -a" al calls the alias 'li' • Parameters added to alias will be added at the end of the real command. • The parameter variables ($1, $2, $3 ...etc) cannot be used within aliases. • Aliases are often defined in a file run within a script like ~/.bashrc or

~/.profile with the dot '.‚ command.

Module Contents

Aliases • Alias commands: alias - Displays all the current shell aliases. alias AliasName="command(s)..." - Sets a new alias value.

• Example: # alias cp="cp –i" Replaces the original command cp with cp -i for interactive copying (asks before overwriting files). unalias AliasName - Unsets (deletes) the alias.

Module Contents

Aliases Command search priority When a command is run, bash tries to find the command in the following sequence: • Aliases • Functions • Builtin commands • searching the PATH The first command found is the one which is run. To force using a builtin command instead of an alias or a function (in the case the same command name exists as alias or function), use the command builtin.

# builtin cat /etc/fstab

Module Contents

Functions They are normally used like fast local mini-scripts within a shell which need to be called more than once within the interactive shell or script. Variables can be passed-on to functions and will be recognized as $1 $2 $3 etc. In fact the following variables are local within a function: $1 - $9 - Positional parameters $# - Number of positional parameters $* "$1 $2 $3 …" $@ "$1" "$2" "$3" ...

Module Contents

Functions The positional parameter $0 and all other variables stay global within the shell unless the command local Variablename is given within the function. Within a function, the variable FUNCNAME is used instead of the $0.

Global shell or exported variables can be changed within the function.

Functions do not return variables except for the return number, eg. return 5. The return command will also terminate the function immediately. The return number can then be read as a normal exit value using $?.

Module Contents

Functions In scripts functions are normally included at the top so that they are read in first.

Environment functions can be put into a file and read in with the "." command. Functions may be recursive. No limit is imposed on the number of recursive calls. Functions can be exported, using the command: export -f FunctionName

Module Contents

Functions FunctionName ()

{

command1 ;

command2 ;

}

or

function FunctionName () {

command ;

command ;

}

Module Contents

set Syntax: set [--abefhkmnptuvxBCHP] [-o option] [arg ...] • The set command is used to: • -Display all bash variables and their values as well as the functions. • Example: # set [bash operating attributes] (using options). • -Assign values to positional parameters: • Example: # set aaa bbb ccc ($1 $2 $3) • The above assigns the value aaa to $1, bbb to $2 and ccc to $3.

Module Contents

unset Syntax: unset [-fv] [name ...] • For each name, remove the corresponding variable

or function. • Each unset variable or function is removed from the

environment passed to subsequent commands. If any of RANDOM, SECONDS, LINENO, HISTCMD, FUNCNAME, GROUPS, DIRSTACK are unset, they lose their special properties, even if they are subsequently reset. The exit status is true unless a name does not exist or is read-only.

Module Contents

unset If no options are supplied, or the -v option is given, the name refers to a shell variable. Read-only variables may not be unset.

# unset -v

# unset -f

The following examples delete the variable DISPLAY, and the function startx respectively.

# unset DISPLAY

# unset -f startx

Module Contents

SHELL Scripts Basic Shell Scripting – how to create a Shell script 1. Use any text editor to edit the script file; depending on Linux distribution

you may use vi / vim, joe, jed, pico, nano editors. 2. Change the created script file permissions (by default they are of 644

value, they should be of 755 value – do chmod 755 filename). 3. Place the script file in one of the directories listed on PATH variable (you

may check the variable content by typing in the command line: echo $PATH.

4. Run the script file by typing in the command line: script_file_name

or ./script_file_name

Module Contents

SHELL Scripts Basic Shell Scripting 1. Keywords !, case, do, done, elif, else, esac, fi, for, function,

if, in, select, then, until,

while, {, }, time, [, ], #

2. Special variables – $0 - the script name (can be displayed/accesst from the script

body) – $1..$9 - the command line arguments (the first can be reffered as $1,

the second as $2, etc.) – $* - list of all command line arguments – $@ - table of all command line arguments – $? - status of the last executed command – $# - number of all arguments the script was executed with

Module Contents

SHELL Scripts Basic Shell Scripting 3. System variables The list of available system variables can be listes as: env

The main system variables include: SHELL - system shell USER - user name (you) HOME - home user directory PS1 - shell command line prompt EDITOR - default editor PATH - default diretories list MAIL - default mail directory

Module Contents

SHELL Scripts Basic Shell Scripting 4. Variables

a) scalar variables - How to declare? - assign a value and that’s it - What types? - integer variables x=3 - string variables str="a string" or

str=‘a string’

for example person="John Smith"

Module Contents

SHELL Scripts Basic Shell Scripting As mentioned before, variables do not have to be declared – first

assignment of a value to a variable makes it declared, for example: X=3

n order to refer to the variable value a $ character has to be added at the beginning of the variable name, for example:

Y=$X

which will assign a value fo the variable X to the variable Y. E variable value can be also displayed on the screen using echo command:

echo $X

Module Contents

SHELL Scripts Basic Shell Scripting Integer variables may be a subject of different arithmetic operations.

These can be done using the following operators: + - addition, – - subtraction, * - multiplication, / - division, % - division (modulo). Arithmetic operations can be done using two commands: let and

expr or $[] expression. The way they are used is shown in the example.

Module Contents

SHELL Scripts 5. Tables Table can be assing as: table=(value1 value2 … valueN)

or table[0]=1

table[1]=3

...

table[N]=N

Module Contents

SHELL Scripts Using tables: ${a[3]} - using 4-th element (indexes start from 0) of the table. ${a[$i]} - using i-th element of the table, ${a[*]} - using all elements of the table, ${a[@]} - using all elements of the table, ${#a[0]} - lenght of the first element in the table, ${#a[*]} - table length, ${#a[@]} - table length. Tables do not have to be declared or allocated – this is done

automatically. Not assigned elements do not exist. tablle[11]=3 - this table is of size 1

Module Contents

SHELL Scripts Tables do not to have to be continuous: table[0]=1

table[2]=3

The above table is of size 2, the element with index 1 does not exist. To delete a selected table element unset command is used. unset table[2]

The above command will delete the table element of index 2 so the table size is 1 from now.

By calling unset table[*] or unset table[@] the table will be deleted as whole.

Module Contents

SHELL Scripts 6. Control instructions These inlcude: for, while, until - loop instructions if, case - condition instructions test - test instruction

7. Conditional instructions

if instruction

if condition if condition

then then

command command1

fi else

command2

fi

Module Contents

SHELL Scripts 7. Conditional instructions

if instruction

if condition case $variable

in

then value1) command1;;

command1 value2) command2;;

elif condition *) command;;

command2 esac

else

command3

fi

Module Contents

SHELL Scripts for

while - loops

until

for VARIABLE in 1 2 3 4 5 .. N

do

command1

command2

commandN

done

for i in 1 2 3 4 5

do

echo "Welcome $i times"

done

Module Contents

SHELL Scripts for (( EXP1; EXP2; EXP3 ))

do

command1

command2

command3

done

while [ condition ]

do

command1

command2

command3

done

Module Contents

SHELL Scripts test - logical test instruction

syntax:

test condition or just like [ condition]

You can test:

a) relations between integers -lt - less than [ $# –lt 2 ]

-gt - greater than [ $a –gt $b ]

-le - leser equal [ $a –le 1 ]

-ge - greater equal [ $a –ge 2 ]

-eq - equal [ $a –eq $b ]

-ne - not equal [ $c –ne 0 ]

b) relations between strings == - equal [ "$a" == "q" ]

!= - not equal [ "$a" != "x" ]

-n - empty [ -n "$a" ]

-z - not empty [ -z" "$1" ]

Module Contents

SHELL Scripts c) files informaiton [ -option path/file ] option: -a - file exists -b - file exists and this is a special block file -c - file exists and this is a special character file -e - file exists -L - file exists and this is a symbolic link -d - file exists and this is a directory -r - read right set -w - write right set -x - execution right set -f - file exists and this is an ordinary file -p - file exists and this is a pipe -N - file exists and was modified since its last read d) combined files information [ path/file1 -option path/file2 ] option: -nt, -ot - file1 is newer than file2

Module Contents

SHELL Scripts Complex conditions can be built using –o (logical OR) or –a (logical AND) option. ...

if [ $# –le 3 –a $# –ge 1 ]

then

...

fi

In the example above between 1-3 arguments are expected at the script execution. ...

if [ -f file –o –d file]

then

...

fi

In the about example the file is expected to be normal file or directory.

Module Contents

The && and || conditional branching The exit code can be used to execute another command (only one) depending upon its success or its failure. The double ampersand '&&' is used to designate the command to run if the exit code is success (0). The double pipe '||' designates the command to run if the exit code is not a success (1-255). # ifconfig ppp0 && echo "pppd running" || echo "pppd not running„

If the command ifconfig ppp0 succeeds then the command echo "pppd running" will be executed (&&) otherwise the command echo "pppd not running" will be executed.

Module Contents

Mailing messages to root from a script # mail -s "subject" dest_mail_address "message..„

# program | mail -s "subject" destination_mail_address

# mail -s "subject" dest_mail_address <<EOM

message body.......

EOM

Example: # df | mail -s "HD Space on $(date)" root

Mails the result of the command df to the local root user.

Module Contents

Common SQL Implementations for Linux Some of the more common choices in Linux include the following: • MySQL - This SQL Implementation is owned by Suns, and is released

under the GPL. Most major Linux distributions will include MySQL in their package databases.

• PostgreSQL - Released under the BSD license, PostgreSQL was evolved from Ingres software.

• (PostgreSQL= post-Ingres SQL). It’s available as multiple packages in most Linux distributions.

• SQLite – To implement SQL as a library, you need SQLite. SQLite is intended to provide users and programs a way to store data using a SQL interface within the program. SQLite3 can be used to manipulate SQLite databases for major Linux distros.

Module Contents

Common SQL Implementations for Linux SQL is used to access relational databases. Each database contains more or less tables which in turn contain more or less rows and columns. Hereby a single row is seen as a separate object with features represented by the tables' columns. To access a table's data you first have to connect to its database. 1. mysql -u USERNAME -p PASSWORD

2. use DATABASE

to manipulate SQLite databases for major Linux distros.

Module Contents

Basic SQL Commands • SELECT A SELECT statement retrieves zero or more rows from one or more database tables or database views. In most applications, SELECT is the most commonly used Data Manipulation Language (DML) command. As SQL is a declarative programming language, SELECT queries specify a result set, but do not specify how to calculate it. The database translates the query into a "query plan" which may vary between executions, database versions and database software. This functionality is called the "query optimizer" as it is responsible for finding the best possible execution plan for the query, within applicable constraints.

Module Contents

Basic SQL Commands The SELECT statement has many optional clauses: • WHERE specifies which rows to retrieve. • GROUP BY groups rows sharing a property so

that an aggregate function can be applied to each group.

• HAVING selects among the groups defined by the GROUP BY clause

• ORDER BY specifies an order in which to return the rows.

Module Contents

Basic SQL Commands Examples: • Given a table TAB, the query „SELECT * FROM TAB”

will result in all the elements of all the rows of the table being shown.

• With the same table, the query „SELECT C1 FROM TAB” will result in the elements from the column C1 of

• all the rows of the table being shown. • With the same table, the query „SELECT * FROM TAB WHERE C1 = 1” will result in all the elements of all

• the rows where the value of column C1 is '1' being shown.

Module Contents

Basic SQL Commands • WHE RE A WHERE clause specifies that a SQL statement should only affect rows that meet specified criteria. The criteria are expressed in the form of predicates. WHERE clauses are not mandatory clauses of SQL statements, but should be used to limit the number of rows affected by a SQL DML statement or returned by a query. The following query returns only those rows from table mytable where the value in column mycol is greater than 100. SELECT *

FROM mytable

WHERE mycol > 100

Module Contents

Basic SQL Commands • DI STINCT

DISTINCT will eliminate all duplicate rows from the selection. DISTINCT ON column will eliminate all duplicates in the specified column; this is equivalent to using GROUP BY column. ALL will return all candidate rows, including duplicates.

SELECT DISTINCT jobTitle FROM employees;

Module Contents

Basic SQL Commands • HAVING A HAVING clause in SQL specifies that an SQL SELECT statement should only return rows where aggregate values meet the specified conditions. It was added to the SQL language because the WHERE keyword could not be used with aggregate functions. To return a list of department IDs whose total sales exceeded $1000 on the date of January 1, 2000, along with the sum of their sales on that date: SELECT DeptID, SUM(SaleAmount)

FROM Sales

WHERE SaleDate = '01-Jan-2000'

GROUP BY DeptID

HAVING SUM(SaleAmount) > 1000

Module Contents

Basic SQL Commands • ORDE R B Y

The ORDER BY clause allows a user to specify that he/she wishes the rows sorted according to the ASCending or DESCending mode operator.

SELECT * FROM Employees

ORDER BY LastName, FirstName

Module Contents

Basic SQL Commands • IN

IN will find any values existing in a set of candidates.

SELECT ename WHERE ename IN ('value1',

'value2', ...)

All rows match the predicate if their value is one of the candidate set of values. This is the same behavior as

SELECT ename WHERE ename='value1' OR

ename='value2'

except that the latter could allow comparison of several columns, which each IN clause does not. For a larger number of candidates, IN is less verbose.

Module Contents

Basic SQL Commands • BETWEEN

BETWEEN will find any values within a range.

SELECT ename WHERE ename BETWEEN 'value1'

AND 'value2'

All rows match the predicate if their value is between 'value1' and 'value2', inclusive.

Module Contents

Basic SQL Commands • LIKE

LIKE will find a string fitting a certain description.

• Ending Wildcard – Find any string that begins with the letter 'S'

SELECT ename FROM emp WHERE ename LIKE 'S%';

• Leading Wildcard – Find any string that ends with the letter 'S'

SELECT ename FROM emp WHERE ename LIKE '%S';

• Multiple Wildcards – Find any string that contains, anywhere, the letter 'S'

SELECT ename FROM emp WHERE ename LIKE '%S%';

Module Contents

Basic SQL Commands • Single Character Wildcard

– Find any string that contains the letter 'A' followed by any single

character followed by the letter 'E' SELECT ename FROM emp WHERE ename LIKE '%A_E%';

SQL programmers need to be aware that the LIKE predicate typically performs a search without the normal performance benefit of indexes. Using '=', '<>', etc.. instead will increase performance. Users of the LIKE predicate should be aware that case sensitivity (e.g., 'S' versus 's') may be different based upon database product or configuration.

Module Contents

Basic SQL Commands • UNION In SQL the UNION clause combines the results of two SQL queries into a single table of all matching rows. The two queries must result in the same number of columns and compatible data types in order to unite. Any duplicate records are automatically removed unless UNION ALL is used. UNION does not guarantee the order of rows. Rows from the second operand may appear before, after, or mixed with rows from the first operand. In situations where a specific order is desired, ORDER BY must be used. Note that UNION ALL may be much faster than plain UNION. Executing below statement will output combined rsults: SELECT * FROM sales2005

UNION

SELECT * FROM sales2006;

Module Contents

Basic SQL Commands • JOIN

A SQL join clause combines records from two or more tables in a database. It creates a set that can be saved as a table or used as is. A JOIN is a means for combining fields from two tables by using values common to each. ANSI standard SQL specifies four types of JOINs: INNER, OUTER, LEFT, and RIGHT. In special cases, a table (base table, view, or joined table) can JOIN to itself in a self-join. A programmer writes a JOIN predicate to identify the records for joining. If the evaluated predicate is true, the combined record is then produced in the expected format, a record set or a temporary table.

Module Contents

Basic SQL Commands SELECT column_list FROM table_1 [INNER | LEFT | RIGHT] table_2 ON conditions_2 [INNER | LEFT | RIGHT] table_3 ON conditions_3 ... WHERE conditions

LEFT JOIN can be used when you want to retrieve the data from the main table (table_11) even if there is no match in other tables (table_2, table_3....). While RIGHT JOIN is used to retrieve the data from all other tables (table_2, table_3...) even if there is no match in the main table.

Module Contents

Basic SQL Commands • INNER JOIN An inner join is the most common join operation used in applications and can be regarded as the default join-type. Inner join creates a new result table by combining column values of two tables (A and B) based upon the join-predicate. The query compares each row of A with each row of B to find all pairs of rows which satisfy the join-predicate. When the join-predicate is satisfied, column values for each matched pair of rows of A and B are combined into a result row. The result of the join can be defined as the outcome of first taking the Cartesian product (or cross-join) of all records in the tables (combining every record in table A with every record in table B)—then return all records which satisfy the join predicate.

Module Contents

Basic SQL Commands Current SQL implementations normally use other approaches like a hash join or a sort-merge join where possible, since computing the Cartesian product is very inefficient. SQL specifies two different syntactical ways to express joins: "explicit join notation" and "implicit join notation". The "explicit join notation" uses the JOIN keyword to specify the table to join, and the ON keyword to specify the predicates for the join, as in the following example: SELECT *

FROM employee INNER JOIN department

ON employee.DepartmentID = department.DepartmentID;

Module Contents

Basic SQL Commands

The "implicit join notation" simply lists the tables for joining (in the FROM clause of the SELECT statement), using commas to separate them. Thus, it specifies a cross-join, and the WHERE clause may apply additional filter-predicates (which function comparably to the join-predicates in the explicit notation).

Module Contents

Basic SQL Commands • INSERT INSERT INTO table [ ( column [, ...] ) ]

{ VALUES ( expression [, ...] ) | SELECT query }

INSERT allows one to insert new rows into a table. One can insert a single row at a time or several rows as a result of a query. The columns in the target list may be listed in any order. In every column not present in the target list, its default value will be inserted. If a column has no declared default value it will be assumed as NULL. If the expression for each column is not of the correct data type, automatic type coercion will be attempted. INSERT INTO tbl_movies(title,year) VALUES(‘Alexander’,’2004’)

Module Contents

Basic SQL Commands • UPDATE UPDATE table SET column = expression [, ...]

[ FROM fromlist ]

[ WHERE condition ]

UPDATE changes the values of the columns specified for all rows which satisfy condition. Only the columns to be modified need appear as column. Array references use the same syntax found in SELECT. That is, either single array elements, a range of array elements or the entire array may be replaced with a single query. You must have write access to the table in order to modify it, as well as read access to any table whose values are mentioned in the WHERE condition. UPDATE tbl_movies SET genre = 'Dramatic' WHERE genre = 'Drama';

Exercise

EXERCISE 5.1 – aliases 1. Check list of existing aliases # alias 2. Define lf alias as: # alias lf=”ls -al” 3. In the command line type in: # lf / # lf $HOME 4. Undefine the lf alias # unalias lf 5. In the command line type in: # lf / # lf $HOME

Exercise

EXERCISE 5.2 – functions 1. Write a follwing script file (give it any name you want)

#!/bin/bash

function count () {

for filenane in $1/*

Do

let ”cnt=cnt+1”

Done

}

Cnt=0

count $1

echo $cnt

Exercise

EXERCISE 5.2 – shell scripts 2. Write a follwing script file (give it any name you want) Example 1: Handling improper number of script arguments #!/bin/bash if [ $# -lt 2 ] then echo “----------------------------------------------------------------“ echo –e “\tScript <$0> should be executed with at least 2 arguments” echo “----------------------------------------------------------------“ else echo “----------------------------------------------------------------“ echo –e “\tScript <$0> executed with $# parameters: $@” echo “----------------------------------------------------------------“ fi

Exercise

EXERCISE 5.2 – shell scripts 3. Write a follwing script file (give it any name you want) Example 2: Simple calculator and user interaction

#!/bin/bash

while [ -z “$arg1” ] #will be repeated until a data will be entered

do

read –p “Enter argument1: “ arg1

done

while [ -z “$arg2” ] #will be repeated until a data will be entered

do

read –p “Enter argument2: “ arg2

Exercise

EXERCISE 5.2 – shell scripts 4. Write a follwing script file (give it any name you want) Example 2: Simple calculator and user interaction - continued done echo “You’ve entered: arg1=$arg1 and arg2=$arg2” let “addition=arg1+arg2” let “subtraction=arg1-arg2” let “multiplication=arg1*arg2” let “division=arg1 / arg2” let “reminder=arg1 % arg2” echo –e “results:\n” echo “$arg1+$arg2=$addition” echo “$arg1-$arg2=$subtraction” echo “$arg1*$arg2=$multiplication” echo “$arg1/$arg2=($division+$reminder/$arg2)”

Exercise

EXERCISE 5.2 – shell scripts 4. Write a follwing script file (give it any name you want) Example 3: Listing all directories in the location given as the script argument #!/bin/bash echo “Directory <$1> contains the following directories:” ls $1 | while read file do if [ -d $1/$file ] then echo “[$file]” fi done

Exercise

EXERCISE 5.2 – shell scripts 4. Write a follwing script file (give it any name you want) Example 4: List files which size is an odd number #!/bin/bash echo “Directory <$1> contains the following filenames of od size:” ls –l $1 | while read file_parm do size=`echo $file_parm | cut –f 5 –d “ “` name=`echo $file_parm | cut –f 9 –d “ “` let “div=size%2" if [ ! -d $name ]; then if [ $div -ne 0 ] then echo "[$name : $size]" fi fi done

Exercise

EXERCISE 5.2 – shell scripts 5. Tasks:

Please write a shell script which would count the number of files in a directory given as the script argument. The script you write should be executed as: script1 directory_name

Please write shell script which would count (total) the sum of file sizes in the given directory. It should be executed as: script2 directory_name

Please write shell script which would delete only the files in the directory give as the script argument which are of size that is an even number. Make each deletion to be confirmed by pressing “d” key. The script should be executed as: script3 directory_name

Exercise

EXERCISE 5.2 – SQL basics 1. Check if you have mysql client program installed (yum whatprovides

mysql).

2. Install the mysql server on your CentOS machine (yum whatprovides mysqld). You may try also with Debian too, but later. Is it installed? If not you should install it (yum install mysql-server).

3. Start the mysql server (service mysqld start).

4. As root execute mysql command and in the mysql command line change the default table to test (use test;).

Exercise

EXERCISE 5.2 – SQL basics 5. In the test database create table pet:

create table pet (name VARCHAR(100), age INT, sex CHAR(1));

6. Insert one row into the pet table:

insert into pet (name, age, sex) values (’Rex’,’10’,’M’);

And then add couple of more dogs in the same format.

7. Check what is in the table (select * from pet;).

8. You can also serch for a specified data (select * from pet where name=’Rex’;).

9. You can also update a given record, try change age for any dog (update pet set age=’new_age_value’ where name=’name_of _the_dog’;);