- To truncate a float to int:
INT=${FLOAT/\.*}
- To split a string (of 2 words) into its components:
FIRST_WORD=${STRING%% *}
,SECOND_WORD=${STRING#* }
- To do simple floating point arithmetic, use
bc
:AVERAGE=$(echo "scale=2; ($FLOAT1 + $FLOAT2 ) / 2" | bc )
- Conditional
if
statement:if [[ $INT1 -gt $INT2 ]]; then echo greater; fi
- 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=2E_BADARGS=65if [ $# -ne $EXPECTED_ARGS ]; thenecho "Usage: ./script_name arg1 arg2"echo " Example: ./sum 1 2"exit $E_BADARGSfi
- To find the process ID of a running process, use
pgrep
:pgrep -fl PROCESS_NAME - 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}')
- Find files that contain a text string:
Thegrep -lir "text to find" *-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 20, 2010
Bash chit-sheet
Some simple tricks that can make bash scripting a breeze:
Labels:
arguments,
bash,
floating point,
if,
kill,
process ID,
string