The Return of the Value
Okay, so the only way to return a value from a function is with a side effect. What the heck do you do to return values?
One option is to have the function create real output and capture it.
I've seen a handful, but I like this:
One option is to have the function create real output and capture it.
This works, but costs the execution of a subshell each time you call the function. A more efficient approach is to capture output in a global, and use a naming convention to keep from accidentally stepping on a some other variable with the same name.#!/bin/bash
date_diff() {
t2=$(date -d "$1" +%s)
t1=$(date -d "$2" +%s)
echo $((t1-t2))
}
secs=$(date_diff "Dec 25" "now")
echo "$secs more shopping seconds until Christmas"
I've seen a handful, but I like this:
Try using the name of the function, preceded by an underscore, to hold the return value of the latest call.date_diff() {
t2=$(date -d "$1" +%s)
t1=$(date -d "$2" +%s)
_date_diff=$((t1-t2))
}
date_diff
echo "$_date_diff more shopping seconds until Christmas"
0 Comments:
Post a Comment
<< Home