Caleb
Caleb

Reputation: 51

Listing time every second as a Bash script

first time here as I've finally started to learn programming. Anyway, I'm just trying to print the time in nanoseconds every second here, and I have this:

#!/usr/bin/env bash

while true;
do
 date=(date +%N) ;
 echo $date ;
 sleep  1 ;
done

Now, that simply yields a string of date's, which isn't what I want. What is wrong? My learning has been rather messy, so I hope you'll excuse me for this if it's really simple. Also, I did manage to fine this, that worked on the prompt:

while true ; do date +%N ; sleep 1 ; done

But that obviously doesn't work as a script?

Edit, if anyone sees this: Ahh, this does indeed fix my error. I note you didn't add a ; Is that because I only defined a variable? Also, could you explain what the $ does? I thought it was for calling variables. And I see that the above line will indeed work as a script; I had expected the output of date to not be put on the screen.

Upvotes: 5

Views: 10472

Answers (4)

anjchang
anjchang

Reputation: 493

A one liner using shell commands

while [ 1 ] ; do echo -en "$(date +%T)\r" ; sleep 1; done

exit using CTRL+C

Upvotes: 1

Dmitry Spikhalsky
Dmitry Spikhalsky

Reputation: 5820

This version should work

#!/bin/bash

while true; do
 date=$(date +"%N")
 echo Current date is $date
 sleep 1
done

Upvotes: 2

Aleksandr Poteriachin
Aleksandr Poteriachin

Reputation: 11

You can enclose your command between "`" (Backtick) too. For example:

date=`date +%N`

Regards

Upvotes: 1

codaddict
codaddict

Reputation: 454930

Change

date=(date +%N) ;

to

date=$(date +%N)

Upvotes: 7

Related Questions