Showing posts with label bash. Show all posts
Showing posts with label bash. Show all posts

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.


Thursday, May 6, 2010

Add commands to bash

This post is about adding user defined commands to bash so that you can run applications only using the command rather than specifying the whole path of the application executable.

The code provided here has been tested on Ubuntu 9.10 (Karmic Koala).

There are two ways to accomplish the mission, the first is to put your application is the default path that bash already looks into while trying to execute your command, and the second is to add another location as a path that bash must check.

For the first option, run $PATH in the terminal. Your terminal output would look something like

bash: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

If you put your scripts/executables in any of the above locations, bash will find it and execute it without you having to specify the whole path.

For the second option, you need to edit the ~/.bashrc file and add the location of the executable to the PATH locations. Suppose this location is /home/pbhat/bin/. Concatenate the following line to the end of ~/.bashrc file.

PATH=$PATH:/home/pbhat/bin
export PATH

Save and close the file and now run the following command in the terminal:
source ~.bashrc

Unless you run this command the updated path will not show up.