Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
964 views
in Technique[技术] by (71.8m points)

linux - Extending a script to loop over multiple files and generate output names

I have following script (named vid2gif.sh) to convert a video file to gif:

#! /bin/bash
ffmpeg -i $1 /tmp/gif/out%04d.gif
gifsicle --delay=10 --loop /tmp/gif/*.gif > $2

I can convert a file using command:

vid2gif.sh myvid.mp4 myvid.gif

How can I make it to convert all mp4 files in a folder? That is, how can I make following command work:

vid2gif.sh *.mp4

The script should output files as *.gif. Thanks for your help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
#!/bin/sh
for f; do
  tempdir=$(mktemp -t -d gifdir.XXXXXX)
  ffmpeg -i "$f" "$tempdir/out%04d.gif"
  gifsicle --delay=10 --loop "$tempdir"/*.gif >"${f%.*}.gif"
  rm -rf "$tempdir"
done

Let's go over how this works:

  1. Iteration

    for f; do
    

    is equivalent to for f in "$@"; that is to say, it loops over all command-line arguments. If instead you wanted to loop over all MP4s in the current directory, this would be for f in *.mp4; do, or to loop over all MP4s named in the directory passed as the first command line argument, it would be for f in "$1"/*.mp4; do. To support either usage -- but go with the first one if no directory is passed -- it would be for f in "${1:-.}"/*.mp4; do.

  2. Temporary directory use

    Because the original script would reuse /tmp/gif for everything, you'd get files from one input source being used in others. This is best avoided by creating a new temporary directory for each input file, which mktemp will automate.

  3. Creating the .gif name

    "${f%.*}" is a parameter expansion which removes everything after the last . in a file; see BashFAQ #100 for documentation on string manipulation in bash in general, including this particular form.

    Thus, "${f%.*}.gif" strips the existing extension, and adds a .gif extension.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...