Ever wanted to have a real-time clock on your linux terminal? We can create one with a single line of bash, like so:
while echo -en "$(date)\r"; do sleep 1; done
Let’s look at how this works:
dateis a common unix tool used to print the current date and time. The
$(...)means that the
datecommand is run, and the output is placed here instead. For example, if logged in as root,
echo "I am $(whoami)!"is the same as
echo "I am root!".
echo -enwill print the output of
$(date). -e allows escaped characters (the
\rin this case), and
-nmeans echo will not add a newline character to the end of the line.
\ris a carriage return character. This returns the cursor to the beginning of the current line, which means the next thing to print will overwrite anything on that line.
while <condition>; do <commands>; doneis a standard while loop;
<commands>will be run while
true(ie: execution is successful).
sleep 1will pause program execution for 1 second.
Altogether, it means we will print the date every second, overwriting the previously printed date, until we end the program (ctrl-c) or until the
echo command fails (which is unlikely to happen).