sample.shell.txt 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #!/bin/bash
  2. # Simple line count example, using bash
  3. #
  4. # Bash tutorial: http://linuxconfig.org/Bash_scripting_Tutorial#8-2-read-file-into-bash-array
  5. # My scripting link: http://www.macs.hw.ac.uk/~hwloidl/docs/index.html#scripting
  6. #
  7. # Usage: ./line_count.sh file
  8. # -----------------------------------------------------------------------------
  9. # Link filedescriptor 10 with stdin
  10. exec 10<&0
  11. # stdin replaced with a file supplied as a first argument
  12. exec < $1
  13. # remember the name of the input file
  14. in=$1
  15. # init
  16. file="current_line.txt"
  17. let count=0
  18. # this while loop iterates over all lines of the file
  19. while read LINE
  20. do
  21. # increase line counter
  22. ((count++))
  23. # write current line to a tmp file with name $file (not needed for counting)
  24. echo $LINE > $file
  25. # this checks the return code of echo (not needed for writing; just for demo)
  26. if [ $? -ne 0 ]
  27. then echo "Error in writing to file ${file}; check its permissions!"
  28. fi
  29. done
  30. echo "Number of lines: $count"
  31. echo "The last line of the file is: `cat ${file}`"
  32. # Note: You can achieve the same by just using the tool wc like this
  33. echo "Expected number of lines: `wc -l $in`"
  34. # restore stdin from filedescriptor 10
  35. # and close filedescriptor 10
  36. exec 0<&10 10<&-