Current time/date as a variable in BASH and stopping a program with a script

When you do

NOW=`date '+%F_%H:%M:%S'`

or, using more modern syntax,

NOW=$( date '+%F_%H:%M:%S' )

the variable NOW will be set to the output of the date command at the time when that line is executed. If you do this in ~/.bashrc, then $NOW will be a timestamp that tells you when you started the current interactive shell session.

You could also set the variable's value with

printf -v NOW '%(%F_%H:%M:%S)T' -1

if you're using bash release 4.2 or later. This prints the timestamp directly into the variable without calling date.

In the script that you are showing, the variable NOW is being set when the script is run (this is what you want).

When the assignment

filename="/home/pi/gets/$NOW.jpg"

is carried out, the shell will expand the variable in the string. It does this even though it is in double quotes. Single quotes stops the shell from expanding embedded variables (this is not what you want in this case).

Note that you don't seem to actually use the filename variable in the call to raspistill though, so I'm not certain why you set its value, unless you just want it outputted by echo at the end.

In the rest of the code, you should double quote the $NOW variable expansion (and $filename). If you don't, and later change how you define NOW so that it includes spaces or wildcards (filename globbing patterns), the commands that use $NOW may fail to parse their command line properly.

Compare, e.g.,

string="hello * there"

printf 'the string is "%s"\n' $string

with

string="hello * there"

printf 'the string is "%s"\n' "$string"

Related things:

  • About backticks in command substitutions: Have backticks (i.e. `cmd`) in *sh shells been deprecated?

  • About quoting variable expansions: Security implications of forgetting to quote a variable in bash/POSIX shells and Why does my shell script choke on whitespace or other special characters?


This answer is a few practical pointers:

  1. Don't use characters such as : for naming files! Before using any non-alphanumeric character, ask yourself whether it could possibly mess up any future script or command line one-liner. Use a dash or underline instead, or just squish the elements together with no delimiter.

  2. Since your question indicates that you are using bash, you should know that recent versions of that shell include a native version of date-spec output withing the shell's own printf command. Use it like so:

    printf "%(%F_%H%M%S)T"
    

    or

    NOW=$(printf "%(%F_%H%M%S)T")
    

    or even

    printf -v NOW "%(%F_%H%M%S)T"
    

    (which avoids forking an extra process)

  3. The bash version of printing a date-spec has the additional advantage of two features not present otherwise: "-1 represents the current time, and -2 represents the time the shell was invoked. If no argument is specified, conversion behaves as if -1 had been given." For example,

    printf -v THEN "%(%F_%H%M%S)T" -2