-1

how can one make this script work with both input usage scenarios below?

#1    ./script.sh
#2    ./script.sh input.file

contents of script.sh

for i in *.mp4; do ffmpeg -i "$i" "${i%.*}.mp4

scenario #1 is the only one working right now because the file contents above specifically allow one to run script.sh within a directory where all .mp4 files will be targeted.

is it possible to also target an individual file rather than the whole directory, however still keep the other usage scenario #1 available at all times to use.

UPDATE: I do not see how this is related the the question he is commenting about.

Anonymous
  • 503

1 Answers1

1

Just use the argument as the path. You can use a simple trick: /path/to/dir/./ is the same as /path/to/dir/ since ./ means 'the current directory. So for this simple case, you could just do:

#!/bin/bash

for i in "$1"./*.mp4; do 
    ffmpeg -i "$i" "${i%.*}.mp4"; 
done

And then run the script either like this:

cd /path/to/mp4; /path/to/script.sh

Or like this (the final slash is essential):

/path/to/script.sh /path/to/mp4/

The general way of doing this is something like this:

#!/bin/bash

## Assign the 1st argument to the variable "target"
target=$1
## If $target has no value (if $1 was empty), set it to "."
target=${target:="."}

for i in "$target"/*.mp4; do 
    ffmpeg -i "$i" "${i%.*}.mp4"; 
done

The variable isn't actually needed, you can just do:

#!/bin/sh
for i in ${1-.}/*.mp4; do 
    echo ffmpeg -i "$i" "${i%.*}.mp4"; 
done

Or:

#!/bin/sh

if [ -z "$1" ]; then
  target="."
else
  target="$1"
fi

for i in "$target"/*.mp4; do 
    ffmpeg -i "$i" "${i%.*}.mp4"; 
done
terdon
  • 242,166
  • "$1"/./*.mp4 would default to the root directory if $1 is empty, not the current dir. And it doesn't need a trailing slash, but "$1"./*.mp4 would. ${var:=.} should be POSIX, but target=${target:="."} seems a bit redundant with essentially a double assignment. I think just "${1-.}"/*.mp4 should do if one wants to be brief... – ilkkachu Jun 06 '19 at 20:04
  • 1
    @ilkkachu argh, yes, of course. I'd even seen that and fixed it in the version I was using for testing but forgot to copy it to the answer! Thanks. And you're quite right about ${1-.}, for some reason that hadn't occurred to me. – terdon Jun 06 '19 at 22:47
  • (actually, if $1 is /, then "${1-.}"/*.mp4, expands to //*.mp4 which is allowed to be different from just /*.mp4, but it probably isn't on the most common systems. (I know I've seen a question about the systems where that applies somewhere on the site.) So yeah, maybe the conditional is better.) – ilkkachu Jun 07 '19 at 22:16