1

I have a simple script (timeconvert.sh) that converts seconds into hh:mm:ss format and writes it to a file timeremain.out:

#!/bin/bash
#convert sec to h:m:s
secs=${1:?}

h=$(( secs / 3600 ))
m=$(( ( secs / 60 ) % 60 ))
s=$(( secs % 60 ))

printf "%02d:%02d:%02d\n" $h $m $s > timeremain.out

I am trying to get it to read a file secremain.out as the input for the script but none of the following work:

cat secremain.out | ./timeconvert.sh
./timeconvert.sh < secremain.out

Can anyone suggest the proper syntax to use or an edit to the script to read the file directly?

2 Answers 2

2

Your script reads the seconds from $1 so you can either pass them in on the command line:

secs=$(cat secremain.out)
./timeconvert.sh $secs

# or

./timeconvert.sh $(cat secremain.out)

Or you can change your script to read from stdin:

#!/bin/bash
#convert sec to h:m:s
read secs

If you do the latter then it can read from the file the way you wrote:

cat secremain.out | ./timeconvert.sh
./timeconvert.sh < secremain.out
Sign up to request clarification or add additional context in comments.

1 Comment

Note: $(<file) is a bash shortcut for $(cat file)
0

With this script

: you can both use STDIN or an argument, the script detect itself the context :

#!/bin/bash
#convert sec to h:m:s

if [[ -t 0 ]]; then
    secs=${1:?}
else
    read secs
fi

h=$(( secs / 3600 ))
m=$(( ( secs / 60 ) % 60 ))
s=$(( secs % 60 ))

printf "%02d:%02d:%02d\n" $h $m $s

Usage Examples

./script.sh 120

or

echo 120 | ./script.sh

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.