Thursday, May 20, 2010

Bash chit-sheet

Some simple tricks that can make bash scripting a breeze:
  1. To truncate a float to int:
    INT=${FLOAT/\.*}


  2. To split a string (of 2 words) into its components:
    FIRST_WORD=${STRING%% *},SECOND_WORD=${STRING#* }


  3. To do simple floating point arithmetic, use bc:
    AVERAGE=$(echo "scale=2; ($FLOAT1 + $FLOAT2 ) / 2" | bc )


  4. Conditional if statement:
    if [[ $INT1 -gt $INT2 ]]; then echo greater; fi


  5. To check the number of arguments for a bash script and to issue an error message if the number of arguments if insufficient, use the following code snippet at the top of the script:
    EXPECTED_ARGS=2
    E_BADARGS=65
    if [ $# -ne $EXPECTED_ARGS ]; then
    echo "Usage: ./script_name arg1 arg2"
    echo " Example: ./sum 1 2"
    exit $E_BADARGS
    fi



  6. To find the process ID of a running process, use pgrep:
    pgrep -fl PROCESS_NAME


  7. To kill a process using the process name instead of the process ID, use:
    kill $(ps -ef |grep PROCESS_NAME | grep -v grep | awk '{print $2}')


  8. Find files that contain a text string:
    grep -lir "text to find" *
    The -l switch outputs only the names of files in which the text occurs (instead of each line containing the text), the -i switch ignores the case, and the -r descends into subdirectories.