2
log ()
{
  A=$1
  print "`date '+%m/%d/%y  %H:%M:%S'`: $A"  >> LOGFILE.txt
  print "$A"
}

This is how log function used in most of the shell scripts in our environment. and it's been used in script like below:

if ["blah" != "0"]
then
log "not a zero value"
fi

How does the log function work when the if condition is satisfied?

Can you explain what each line means inside the log function?

1
  • print is not a standard command. Commented Jun 17, 2015 at 23:52

2 Answers 2

3

It would help if you note that you're using ksh or zsh - they both have a print shell built-in.

  1. A=$1
  2. print "`date '+%m/%d/%y  %H:%M:%S'`: $A"  >> LOGFILE.txt
  3. print "$A"

Line 1: $1 means "first argument to function log()". So, assign value of first argument to log to variable named "A".

Line 2: The "grave accents" (a.k.a. "back tics") mean "run the enclosed command and substite its output for the back-tic'ed string. $A means "the value of variable named "A"". So, compose a string by running date, and interpolate the value of A. Shells typically distinguish between rvalue (name assigned to) and lvalue (contents of variable. The ">>" means put it on the end of a file named "LOGFILE".

Line 3: Just write value of variable named "A" to stdout.

The log function is a pretty common way of doing sh-script logging: write one copy of any message to a file with a date stamp, write one copy to stdout. The sh-script runs in a terminal window, and messages just scroll by, but also appear in a file for later debugging.

You invocation of log in the true-clause of the if-statement passes the entire string "not a zero value" as the first formal argument of function log. That's what value gets assigned to variable "A" in line 1.

1
A=$1

assigns the first function argument to the variable A

print "`date '+%m/%d/%y  %H:%M:%S'`: $A"  >> LOGFILE.txt

prints the date and the value of variable A and appends it to LOGFILE.txt

print "$A"

prints the first function argument

BTW, in the line: if ["blah" != "0"]

There should be space after [ and before ], like this:

if [ "blah" != "0" ]

BTW, the print is not a standard command in some shells.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.