Friday, November 6, 2015

Bash - Get function name inside a function


$FUNCNAME has the function name in a bash script which can be used for useful purpose like the following: Script:test.sh
!/bin/sh

WORKID=$(date +%s) ; mkdir $WORKID
LOGFILE=$WORKID/$(basename $0).log

_f_log() {
        echo "$(date):$@" >> $LOGFILE
}

_f_testFunc() {
        local logfile=$1
        local status=$2
        _f_log "$FUNCNAME:$logfile:$status"

}

_f_testFunc /tmp/a.log restart
Executing it:
$ ./test.sh
Result:
$ cat 1446805714/test.sh.log
Fri Nov  6 15:58:34 IST 2015:_f_testFunc:/tmp/a.log:restart

2 comments:

Anirudh said...

Creating scratch-pad directories in the user's home or current directories is not recommended, as they might fill up the user's home disk space or workarea. Since, these are generally of the use-and-throw variety, it's recommended that they be created in the /tmp partition provided for by Linux for just this purpose. But as the /tmp is a common area accessible to all, we must ensure no race conditions in
creation of directories. For example, two users each running mkdir `date +%s` at the same time will create an error in one of the user's account. "mktemp" utility is just what is needed here...

#!/bin/bash -u

perr() {
>&2 echo ${1+"$@"};
}

die() {
perr ${1+"$@"};
exit 1;
}

call_it_quits() {
die "Quitting..";
}

cleanup() {
echo "Cleaning up temp dir... $tempdir";
/bin/rm -rf "$temp_dir";
exit;
}

temp_file() {
mktemp -p "$temp_dir" --suffix=".$PN.log";
}

# like an environmentally conscientious citizen,
# clean up the junk you created when you're done.

trap cleanup EXIT;

PN=$(basename "$0");

# create a safe temp dir under /tmp with the desired suffix
temp_dir=$(TMPDIR='/tmp' mktemp -d --suffix="$(date +%s)") || call_it_quits;

# then create a temp file under the temp dir(created above), with the desired suffix
junk1=$(temp_file);
junk2=$(temp_file);


Actually the $FUNCNAME bash variable can give us a full stack of the calls:

${FUNCNAME[0]} -> who am I
$(FUNCNAME[1]} -> parent
$(FUNCNAME[2]} -> grandparent
...
all the way downto "main"

Baba Fakruddin said...

Nice one

© Jadu Saikia www.UNIXCL.com