Write a shell script to find the average salary of employees of a given designation
Answers
The first example simply counts the number of lines in an input file. It does so by iterating over all lines of a file using a while loop, performing a read operation in the loop header. While there is a line to process, the loop body will be executed in this case simply increasing a counter by ((counter++)). Additionally the current line is written into a file, whose name is specified by the variable file, by echoing the value of the variable line and redirecting the standard output of the variable to $file. the current line to file. The latter is not needed for the line count, of course, but demonstrates how to check for success of an operation: the special variable $? will contain the return code from the previous command (the redirected echo). By Unix convention, success is indicated by a return code of 0, all other values are error code with application specific meaning.
Another important issue to consider is that the integer variable, over which iteration is performed should always count down so that the analysis can find a bound. This might require some restructuring of the code, as in the following example, where an explicit counter z is introduced for this purpose. After the loop, the line count and the contents of the last line are printed, using echo. Of course, there is a Linux command that already implements line-count functionality: wc (for word-count) prints, when called with option -l, the number of lines in the file. We use this to check wether our line count is correct, demonstrating numeric operations on the way.