C2110 UNIX and Programming 9th lesson Bash - Completion (Almost) Petr Kulhánek kulhanek@chemi.muni.cz National Centre for Biomolecular Research, Faculty of Science, Masaryk University, Kamenice 5, CZ-62500 Brno UNIX and programming 9th lesson Homeworks Instructions: 1. Listed tasks are for advanced students. 2. The goal of the tasks is to develop your ability to solve problems that are seemingly unsolvable from the point of available options and resources. In case of bash language, this involves mainly the possibility to work only with integer arithmetic and limited way of rendering into the terminal Tasks: 1. Draw a circle using character "X". The radius of the circle is entered by the user after starting of the script. 2. Draw a circle outline using character "X". The radius of the circle is entered by the user after starting of the script UNIX and programming 9th lesson Contents > Command test • comparing integers and strings > Loops • for vs while, for in, pipes and redirection .0 UNIX and programming 9th lesson Command test, integers The test command is used to compare values and to test types of files and directories (man bash, man test). If the test passes successfully, the return value of the command is set to 0 (true). Integer comparison: test number1 operator number2 Operator: -eq equal to -ne not equal to -It less than -le less than or equal to -gt greater than -ge greater than or equal to Additional information: man bash, man test Alternative notation: must be spaces [[ number1 operator number2 ]] .0 UNIX and programming 9th lesson! Command test, strings Comparison of strings test stringl operator string2 [[ stringl operator string2 ]] Operator: == strings are identical (= also can be used) != strings are different Testing strings test operator stringl [[ operator stringl ]] Operator: -n tests whether the string has not zero length -z tests whether the string has zero length -f tests whether the string has name of an existing file -d tests whether the string has name of an existing directory UNIX and programming 9th lesson Command test, logical operators Logical operators: | | logical or && logical and ! negation • Logical operators can be used to create more complex conditions. • If we do not know priority of the operators, we should use parentheses. • Bash uses lazy evaluation of conditions, which is based on evaluating only the component of the logical condition that must be evaluated to determine the logical value of the whole condition. 10 UNIX and programming 9th lesson -6- Command test, examples [[ (I -ge 5) && (I -le 10) ] ] Is the value of the variable I in the range <5;10>? [[ (I -It 5)||(I -gt 10) ]] or [[ ! ((I -ge 5)&& (I -le 10)) ]] Is the value of the variable I out of the range <5;10>? [ [ I -ne 0 ]] Is the value of the variable I different than zero? [[ "$A" == "test" ]] Does the variable contain string "test"? [ [ "$A" != "test" ]] Does the variable contain different string than string "test" [ [ -z "$A" ] ] Does the variable contain an empty string? [[ -f "$NAME" ]] Is there a file with same name as value of NAME? [ [ ! (-d "$NAME") ] ] Is there no directory with name as the value of NAME? 10 UNIX and programming 9th lesson Exercise I 1. Write a script that will ask the user to gradually enter two numbers. Then, it will print quotient of the two numbers. Treat a possible error of division by zero. 2. Write a script that will create a directory, name of directory is entered by the user after staring the script. Treat the error situation caused by already existing directory. 3. Write a script that asks you to enter an integer. The script will then test whether this is indeed an integer. .0 UNIX and programming 9th lesson Loops: FOR Loop is a control structure that repeatedly performs a series of commands. Both repeating and exit from the loop is managed by condition. if the condition is true, commandl and It is executed before starting the ^ . . ...... ° others commands are executed. loop (counter initialization) Compact notation: for((initialization/condition/change)); do commandl • • • done The counter is updated after the execution of commands. .0 UNIX and programming 9th lesson FOR loop and flowchart for((I = 0; I < N; I = I + 1)); do echo $1 done 10 UNIX and programming 9th lesson -10- Loop: FORvs WHILE if the condition is true, executes commands in the do/done block performed before start of the loop (counter initialization) In addition to cnange of the counter at the end of loop, it is possible to execute other changes in the body of the loop. This is not recommended because it reduces code readability. ►1=1 while [[ $1 -le 10 ] ] ; do echo $1 ((1=1+ 1 )) done Update counter after the execution of commands Counter update can be done anywhere in the body of loop (even at multiple locations). .0 UNIX and programming 9th lesson Prints numbers from 1 to 10 Prints numbers from 10 to 1 for((1=1;I <= 10;I++)); do echo $1 done Variable I is counter. Initialization is governed by rather free rules because the expression is in (()) block. Change: Possible interpretation of the all mathematical expression that can be interpreted within (( )) block, e.g.: ++ value is increased by one -- value is decreased by one others ... for((1=10;I >= 1;I—)); do echo $1 done Condition: Following comparison operators can be used: I = not equal to —— equal to 1 < less I <= less then or equal to 1 > greater then ! >= greater then or equal to can be used only with integers in (()) 10 UNIX and programming 9th lesson FOR loop, change of counter If the variable can be interpreted as integer, following arithmetic operators can be used: ++ variable value incrementated by one A++ variable value decrementated by one A— + sums up two values A = 5 + 6 A = A + 1 subtracts two values A = 5 - 6 A = A - 1 * multiplies two values A = 5 * 6 A = A * 1 / divides two values (integer division) A = 5 / 6 A = A / 1 A=A+3 += increases var/able by value A += 3 A += B -= decreases variable by value A -= 3 A -= B *= multiplies variable by value A *= 3 A *= B /= divides variable by value A/=3 A /= B .0 UNIX and programming 9th lesson Nested loops Loops can be freely nested, Outer loop for((1=1;I <= 10;!++)); do * for((J=l;J<= 10;J++)); do echo "$I $J" done done Inner loop counter of outer loop can affect behavior of inner loop for((1=1;I <= 10;!++)); for((J=l;J <= ); do echo "$I $J" done done The level of nesting is not limited. For loop can be combined with other loops (while, until, for in) or conditions. .0 UNIX and programming 9th lesson Exercise II 1. Write bash scripts for Task 1 and 2. Use for loops instead of while loops. Size of plotted shape is given as the first argument of the script. The script will tests if the entered number of arguments is correct and if the first argument is an integer greater than zero. 2. Edit the task 1, that the rectangle is printed into the terminal. The size should be entered interactively. UNIX and programming 9th lesson Taskl Print a square composed from X characters to the terminal. Side length of the square is entered by the user. 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 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 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 X X X X X X X X X X X X X X X X X X X X X X Please ignore the fact, that it is not visually a square. Number of X characters per line and the number of lines must be the same. 10 UNIX and programming 9th lesson -16- Task 2 Print a triangle composed from X characters to the terminal. Legs of triangle are placed at left and top of the triangle. Leg length of the triangle is entered by the user. 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 X X X X X X X X XXX X X X X X X X X X X X X XXX X X X 10 UNIX and programming 9th lesson -17- Loop FOR ... IN ... Commands in the block do/done (commandl, ...) are executed for each element in the list LIST. In the given run of the loop, variable VAR includes current element from the list LIST for VAR in LIST do commandl $VAR • • • done Compact notation: for VAR in LIST; do commandl $VAR • • • done 10 UNIX and programming 9th lesson -18- Loop FOR ... IN lists for A in a b c; do echo $A done Loops will run three times, characters a, b, c are printed, one character in each run of cycle. It is appropriate to create the list of items algorithmically (using the commands listed in graves - reverse apostrophes). for A in xls *.epsx; do ./process_file $A done for A in x seq 1 0.25 10x; do printf "%8 .3f\n " $A done Command process_file is executed for every file with suffix eps, which is in the current directory. Creates real numbers in the range of 1 to 10 with an increment of 0.25. The numbers will be printed with an accuracy of three decimal places aligned right with 8 character length. Documentation: man seq .0 UNIX and programming 9th lesson Redirection and pipes Read file line by line: pipe while read A; do command2 • • • done < file.txt Redirection to file: for((1=1;I <= 10;I++)); do echo $1 done > file.txt redirection Output of all commands in the loop is redirected to file.txt. .0 UNIX and programming 9th lesson Redirection and pipes - examples for((1=1;I <= 10;I++)); do echo $1 done > file.txt for((1=1;I <= 10;I++)); do echo $1 printf "N=%10d\n" $1 done > file.txt Same functionality rm -f file . txt for((1=1;I <= 10;I++)); do echo $1 » file.txt done Different functionality rm -f file.txt for((1=1;I <= 10;I++)); do echo $1 » file.txt printf "N=%10d\n" $1 done .0 UNIX and programming 9th lesson Exercise III 1. Edit the scripts from the previous exercise in such a way that size of the shapes would be read from standard input and the resulting shape will be printed to a file, the name of this file is entered to standard input by user 2. Write a script that prints real numbers in the range from -10 to 10 with an increment of 0.5. Numbers will be printed including the sign, right-aligned, values will be 10 characters long and with precision one decimal point. 10 UNIX and programming 9th lesson -22- Ho me works 10 UNIX and programming 9th lesson Homework I Explain different behavior of the following scripts. Data.txt file contains five lines. #!/bin/bash 1 = 0 cat data.txt | while read A; do !=$( ($1 + 1) ) done echo $1 prints number 0 #!/bin/bash 1 = 0 while read A; do !=$( ($1 + 1) ) done < data.txt echo $1----1 print number 5 10 UNIX and programming 9th lesson Homework II File rst.out (wolf.ncbr.munixz:/home/kulhanek/Documents/C2110/Lesson09/rst.out) contains the results of molecular dynamics simulation. Your task is to extract the temperature dependence of the simulated system on time from the file, you will save these data to file temp.out, which will contain two columns. First column will be time and second column will be temperature. time temperature NSTEP = Etot BOND 1-4 NB = EELEC = 500 TIME (PS) 942.6248 51.3204 17.7099 ■494 .7423 EKtot ANGLE 1-4 EEL EGB 0.500 TEMP(K) 151.0990 292.3619 981.4071 -164.7991 288.02 PRESS EPtot DIHED VDWAALS RESTRAINT 0.0 791.5258 176.5980 -68.3301 0.1822 EAMBER (non-restraint) 791.3436 Caution: It is forbidden to use commands grep, awk, and also their variants in the script. To solve the task use commands read and while. .0 UNIX and programming 9th lesson Selfstudy functions - for advanced students 10 UNIX and programming 9th lesson Functions - definition Function is a structure that allows to group part of the code so that it can be easily used on multiple locations of the script. Functions result in clean and readable code when some tasks are repeated. Definition: function name () commandl command2 function name{ commandl command2 name() { commandl command2 V alternative notation Arguments of the function are not declared, therefore there is no control of the number of the given arguments, no type control, and functions can not be overloaded. Given arguments are available via special variables #, 1-9, *. The functions are executed as an existing command. Variables in the function are global (it can be changed by using the keyword local). Documantation: man bash, sekce FUNCTIONS. .0 UNIX and programming 9th lesson Function - use # print line - the length is in the first argument function print line () { N=$l for((*=l;J <= N;J++)); do e\ho -n " X" done \ echo "" \ # use function \ print line 10 # Rrint line 10 characters long print line 5^v # pVint line 5 characters long Value of the argument is available via special variable 1 .0 UNIX and programming 9th lesson Exercise 1. Write a script that will print the square, and triangle (similar to task 1 and 2) for one specified length one after another to the terminal. Identify the part that is 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 XXX X X X Please ignore the fact, that it is not visually a square. Number of X characters per line and the number of lines must be the same. 10 UNIX and programming 9th lesson -29-