I have a bash function that fetches values (using curl and cut) and creates a file name from them. Now I want to support a second naming scheme that needs a different set of parameters.
Example:
#!/bin/bash
TEMPLATE="%02i. %s.txt"
foo() {
a="Imagine these to"
b="be set dynamically"
c="42"
filename="$(printf "$TEMPLATE" "$c" "$a")"
# second: filename="$a - $b.txt"
# or: filename="$(printf "%s - %s.txt" "$a" "$b")"
echo "$filename"
# generate file
}
# actual script loops over:
foo
One of the values is a number that should be padded with leading zeros if required, thus printf
in the current implementation.
Is there a way to implement this with just setting a different template globally? This would require that the template can access parameters by index or at least skip some of them.
If not, what are my alternatives? The template is to be chosen by command line parameter and does not change after initialization.
What does not work:
- bash man page suggests that zero length output is not possible (to skip values)
- C's printf man page mentions a "%m$" construct, which apparently is not supported in bash
- the function itself generates the values, so it cannot receive the full filename as parameter