With bash version >= 4.2:
printf "%(%H:%M)T\n"
or
printf -v foo "%(%H:%M)T\n"
echo "$foo"
See: man bash
date +%H:%M
Would be easier, I think :). If you really wanted to chop off the seconds, you could have done
date | sed 's/.* \([0-9]*:[0-9]*\):[0-9]*.*/\1/'
I have another solution for your question .
In the first when use date
the output is like this :
Thu 28 Jan 2021 22:29:40 IST
Then if you want only to show current time in hours and minutes you can use this command :
date | cut -d " " -f5 | cut -d ":" -f1-2
Then the output :
22:29
you can use command
date | awk '{print $4}'| cut -d ':' -f3
as you mentioned using only the date|awk '{print $4}'
pipeline gives you something like this
20:18:19
so as we can see if we want to extract some part of this string then we need a delimiter , for our case it is :
, so we decide to chop on the basis of :
.
Now this delimiter will chop the string into three parts i.e. 20 ,18 and 19 , as we want the second one we use -f2 in our command.
to sum up ,
cut
: chops some string based on delimeter.
-d
: delimeter (here :
)
-f2
: the chopped off token that we want.
Could also potentially use this script to use the system time in a variable
now=$(date +"%m_%d_%Y_%M:%S")
Which outputs as
12_07_2020_34:21
Source: Stackoverflow.com