Showing posts with label shell script. Show all posts
Showing posts with label shell script. Show all posts

Saturday, November 3, 2012

shell script: file information


file=/foo/bar/myfile.txt

File modify date and time

file_modify_date=$(stat -c %y $file | cut -d" " -f1)

file_modify_time="$(stat -c %y $file | cut -d" " -f2 | cut -d":" -f1,2 | tr -d ":")

File directory, name and extension


filename="${file##*/}"  # get filename

extn="${filename##*.}"

filename="${filename%.*}" # removing extension

if [[ $filename == $extn ]]; then
    extn=""
else
    extn=.$extn
fi

dirname="${file%/*}" # get dirname

basename is a good command too

References:

man stat
man basename

http://www.thegeekstuff.com/2010/07/bash-string-manipulation/

Saturday, October 27, 2012

bash script: arithmetic comparison

Arithmetic in BASH is integer math only. You can't do floating point math in Bash; if you need that capability, see Bash FAQ #22.

Remember few tricks

1. use [[ .. ]] for strings and files

2. use (( .. )) for numbers

To compare arithmetic numbers use bc function

$(echo "1.4 < 2.5" | bc)

> and < is for ASCII comparison and so 100 > 75 is false

-gt, -lt is only integer comparison.

This works for me

    if (( $(echo "$mem_util > 75" | bc) == 1 ))
    then
        ...
    fi

I am wondering why there was no floating point support??

References:

http://mywiki.wooledge.org/ArithmeticExpression

http://mywiki.wooledge.org/BashFAQ/031

Thursday, October 18, 2012

linux: RANDOM is so simple

I was impressed with $RANDOM in linux. Simply use $RANDOM to get a random number.

Shell script thingy

Did you know: Hypen, -, is not allowed in script variable names!

a="A"
b="B"

echo "$a_$b"

will print B??!!

it will treat $a_ as the first variable name.

To fix it

echo "${a}_${b}"