Bash – how to convert number to time format in shell script

arithmeticbashffmpegshelltime

I want to cut a video into about 10 minute parts like this.

ffmpeg -i video.mp4 -ss 00:00:00 -t 00:10:00 -c copy 01.mp4
ffmpeg -i video.mp4 -ss 00:10:00 -t 00:10:00 -c copy 02.mp4
ffmpeg -i video.mp4 -ss 00:20:00 -t 00:10:00 -c copy 03.mp4

With for it will be like this.

for i in `seq 10`; do ffmpeg -i video.mp4 -ss 00:${i}0:00 -t 00:10:00 -c copy ${i].mp4; done;

But it works only if duration is under a hour.
How can I convert number to time format in bash shell?

Best Answer

BASH isn't that bad for this problem. You just need to use the very powerful, but underused date command.

for i in {1..10}; do
  hrmin=$(date -u -d@$(($i * 10 * 60)) +"%H:%M")
  outfile=${hrmin/:/-}.mp4
  ffmpeg -i video.mp4 -ss ${hrmin}:00 -t 00:10:00 -c copy ${outfile}
done

date Command Explained

date with a -d flags allows you to set which date you want displayed (instead of the current date and time, which is the default). In this case, I am setting it to a UNIX time by prepending the @ symbol before an integer. The integer in this case is the time in ten minute increments (calculated by the BASH built-in calculator: $((...))).

The + symbol tells date that you would like to specify a format for displaying the results. In our case, we care only about the hour (%H) and the minutes (%M).

And finally, the -u is to display as UTC time instead of local. This is important in this case because we specified the time as UTC when we gave it the UNIX time (UNIX time is always as UTC). The numbers would most likely not start from 0 if you didn't specify -u.

BASH Variable Substitution Explained

The date command gave us just what we needed. But colons in a file name might be problematic/non-standard. So, we substitute the ':' for a '-'. This can be done by the sed or cut or tr command, but because this is such a simple task, why spawn a new subshell when BASH can do it?

Here we use BASH's simple expression substitution. To do this, the variable must be contained within curly braces (${hrmin}) and then use the standard forward slash notation. The first string after the first slash is the search pattern. The second string after the second slash is the substitution.

BASH variable substitution and more can be found at http://tldp.org/LDP/abs/html/parameter-substitution.html.

Related Question