Convert unix time bash loop

archstanton

New Member
Joined
Mar 16, 2024
Messages
1
Reaction score
0
Credits
14
I have a variable called $time that contains

1,1708746085,apples,cars
2,1709764378,pears,bus
3,1709875892,orange,truck

Im trying to iterate over the variable and convert the time from unix time to human readable

var=echo $time |awk -F ","' '{print $2}'
for secs in $var
do
date -d @$secs
done

But it only seems to convert the 1st occurrence and not all them. Suggestion?

At the end of the day im hoping to append the converted times to the end of the items as the 5th column like

1,170874608,apples,cars,Fri, Mar 15 2024 7:37:39 PM
 


I'll try to give a tip or two without actually doing your homework for you. ;)

You need to put double quotes around $time (but not around $var).

It looks like there's an extra single quote in the awk statement and missing backticks around the whole echo...|awk... pipeline. Easier to see if you use
Code:
code tags
here in the forum.

Quoting issues are some of the more annoying things to debug in shell script - right up there with variable scope issues.

Don't use variables named "var", nor integers named "i", etc etc - you might have to maintain that script some day (it happens more often than you might think)

Let me know how it goes.
 
For this script, I would use "while". You might check into the bash while function.
 
For this script, I would use "while". You might check into the bash while function.
I agree. I use "while" for almost everything, so it was fun to play around with "for" while I looked at this.

(Another instance where quote marks are -so- important - the above sentence would cause brain hemorrhage without them!) (as does the spelling of "hemorrhage"!)

I also would have fed the original data into a text file but was pleasantly surprised to see that it actually worked using the "time" variable (and "var", too) to hold multi-line data.
 
(Another instance where quote marks are -so- important - the above sentence would cause brain hemorrhage without them!) (as does the spelling of "hemorrhage"!)

This site supports some markdown. So, you can do for and while if you want.

Put a ` on either side of the code. It's quick and easy, as you don't have to take your hands away from the keyboard to use the mouse to add code that way.

It's pretty handy.
 
Yeah, I remembered seeing it with an extraneous 'a' a few times but couldn't decide where to drop that in. ;)
 

Staff online

Members online


Latest posts

Top