0

I have a collections of scripts I am calling with a wrapper script. I want to update the $date variable each time it is call in the wrapper.

Current code:

start=$(date "+%m-%d-%Y-%T")
echo "Begin Executing Update Jobs at $start"

update1.sh
datetime1=$(date "+%m-%d-%Y-%T")
echo "Executed update 1 - $datetime1"

update2.sh
datetime2=$(date "+%m-%d-%Y-%T")
echo "Executed update 2 - $datetime2"

update3.sh
datetime3=$(date "+%m-%d-%Y-%T")
echo "Executed update 3 - $datetime3"

finish=$(date "+%m-%d-%Y-%T")
echo "Finished Execution at $finish"

Is there a better way to do this than calling the date every time to update it?

1
  • 2
    Use a function. See help function. Commented Aug 14, 2020 at 16:37

2 Answers 2

2

I would recommend writing a reusable function. It looks like all of your lines print a message and then a timestamp. Let's create a function a function that takes the message as an argument ($1), and then prints a timestamp like this:

function printdate {
  echo "$1 $(date "+%m-%d-%Y-%T")"
}

Then you could have a line that says

printdate "Executed update 3 -"

and it would print

Executed update 3 - 08-14-2020-11:48:42
Sign up to request clarification or add additional context in comments.

2 Comments

printf '%s - %(%m-%d-%Y-%T)T\n' "$1" would do same and lighter.
That did it! Thanks.
2

Alternate method using a format string for printf:

#!/usr/bin/env bash
# shellcheck disable=SC2059 # Using variable format strings

declare -r _DATEFMT='%(%m-%d-%Y-%T)T'
declare -r _MSGATFMT="%s at $_DATEFMT\n"
declare -r _UPDATEFMT="Executed update %d - $_DATEFMT\n"

printf "$_MSGATFMT" 'Begin Executing Update Jobs'

for ((upd=1; upd<=3; upd++)); do
  "update$upd.sh"
  printf "$_UPDATEFMT" "$upd"
done

printf "$_MSGATFMT" 'Finished Execution'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.