M
M
maolo2019-04-05 19:19:17
bash
maolo, 2019-04-05 19:19:17

Bash script: how to insert an external variable into a compound command?

There is the following script:

#!/bin/bash
find ./ -type f -name '*.png' | xargs -P 8 -I {} sh -c 'cwebp -q 75 $1 -o "${1%.png}.webp"' _ {} \;

In this form it works fine, but if I try to add a parameter when calling the script (like this: scriptname 85), then everything breaks:
#!/bin/bash
quality=${1:-75}
find ./ -type f -name '*.png' | xargs -P 8 -I {} sh -c 'cwebp -q $quality $1 -o "${1%.png}.webp"' _ {} \;
'                                                                ^^^^^^^^                  '

How can the command be refactored so that the external parameter is inserted?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
maolo, 2019-04-05
@maolo

I apologize for answering myself, but after suffering for another hour, thanks to the Internet, I nevertheless solved the problem - maybe not too elegant, but the main thing that works:

#!/bin/bash
quality=${1:-75}
part1='cwebp -q '
part2=' $1 -o "${1%.png}.webp"'
cmd=$part1$quality$part2
find ./ -type f -name '*.png' | xargs -P 8 -I {} sh -c "$cmd" _ {} \;

And you can call the script either with or without a parameter - by default, the quality is set to 75.
For example, let's create an alias "webp-convert" for the script, then the call will look like this:
$ webp-convert # качество 75
$ webp-convert 90 # качество 90

S
sergey, 2019-04-05
kuzmin @sergueik

double quotes - in single not intepol

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question