Friday 29 March 2013

[Bash]Script to Check C/C++ Header Files

Hello all,
I just wrote a quick bash script to validate the header files from the C/C++ source file. This code just extracts the header file from the source code and runs a quick search in "include" folder, and prints the result. Nothing new, just wanted to write a bash script for learning and fun.

There are many improvements, still to be done. Ideas, suggestions and constructive criticism is welcome.
Here's the code:


  1. #!/bin/bash
  2. #
  3. # Description   : A quick 'n' dirty bash script for validating header files.
  4. # Author        : RahulB
  5. # Usage         : ./validate.sh SourceFile
  6. # Platform      : GNU/Linux
  7. # Greets to     : Anant Sir, Hackuin, b0nd bro, and all g4h members.
  8. #
  9. if [ ! $# = 1 ] ; then             #Checking for exact one command line argument
  10.         printf "Usage : $0 SourceFile \n"      
  11.         exit 1
  12. fi
  13. if [ ! -s $1 ] ; then          #Checking file's existence/ sufficient privilege
  14.         printf "Error : Either file doesn't exist or you don't have sufficient privileges. \n"
  15.         exit 1
  16. fi
  17. declare FILENAME="$1"
  18. declare EXT="${FILENAME##.*}"           #Extracting file extension
  19. declare WD=$(pwd)                       #Saving current working directory
  20. declare VDIR=$(ls -F /usr/include/c++/ | grep '/')  #Extracting version directory
  21. if [ "$EXT" = "cpp" ] ; then       #Determing whether it's C or C++ by file extension
  22.         DIR="/usr/include/c++/$VDIR"    #C++ include directory
  23. elif [ "$EXT" = "c" ] ; then
  24.         DIR='/usr/include/'             #C include directory
  25. else
  26.         printf "Error : Use .cpp for C++ and .c for C source files.\n"
  27.         exit 1;
  28. fi
  29. cat $1 | grep '#include' | cut -d '<' -f2 | cut -d '>' -f1 > demo.log  #Extracting header files' name
  30. cd "$DIR"                                  #Changing directory to include folder
  31. for LINE in $(cat "$WD/demo.log")          #Line-by-line processing
  32. do
  33.         if test -s "$LINE" ; then          #Checking if header file exists or not.
  34.                 printf "$LINE exists. \n"
  35.         else
  36.                 printf "Check the header file $LINE\n"
  37.         fi
  38. done
  39. printf "\n\n"
  40. exit 0                       


Thanks and Regards.
Cheers.

No comments:

Post a Comment