C2110 UNIX and programming Lesson 8 / Module 3 -1C2110 UNIX and programming Petr Kulhanek kulhanek@chemi.muni.cz National Center for Biomolecular Research, Faculty of Science Masaryk University, Kamenice 5, CZ-62500 Brno PS / 2020 Distance form of teaching: Rev1 8. lesson / module 3 C2110 UNIX and programming Lesson 8 / Module 3 -2- Functions C2110 UNIX and programming Lesson 8 / Module 3 -3Functions - Definition Function is a construct that allows you to group a piece of code so that it can be easily used in multiple places in a script. The function therefore simplifies and notation of repetitive tasks. Definition: function name () { command1 command2 ... } function name { command1 command2 ... } name () { command1 command2 ... } alternative notations Function arguments are not declared, so there is no control in the number of arguments, type control, function can not be overloaded. The specified arguments are available via special variables #, 1 to 9, *. Functions are called as an existing command. Variables in the function are global (can be changed using keyword local). Documentation: man bash, section FUNCTIONS. C2110 UNIX and programming Lesson 8 / Module 3 -4Functions - Usage # print line – the length is in the first argument function print_line () { N=$1 for((J=1;J <= N;J++)); do echo –n " X" done echo "" } # use function print_line 10 # print line 10 characters long print_line 5 # print line 5 characters long value of argument is available in a special variable 1 C2110 UNIX and programming Lesson 8 / Module 3 -5- Exercises 1. Write one script that prints a square and a triangle (similar to Tasks 1 and 2) for one specified length one after another to the terminal. In the script, identify the part that is being repeated and rewrite it using function. X X X X X X X X X X X X X X X X X X X X X X X X X X Ignore the fact that it is not visually a square. However, number of X characters for a line and the number of lines must be the same. Possibly use "X " - X and a space.