'How to string interpolate in bash functions

I'm trying to create a function with two parameters, but the second parameter is supposed to go within a string and hence I'm having issues passing that as a parameter

My function (Notice the second instance of $1 -> '["src/**/$1.ts"]')

cov() {
  yarn jest $1 --collectCoverageFrom='["src/**/$1.ts"]' --selectProjects '@bdc/neo' --coverage --verbose
}

Example command

yarn jest auto-fill-vendor.component --collectCoverageFrom='["src/**/auto-fill-vendor.component.ts"]' --selectProjects '@bdc/neo' --coverage --verbose  


Solution 1:[1]

You need to use double quotes to allow parameter expansion.

cov() {
    yarn jest "$1" \
           --collectCoverageFrom="[\"src/**/$1.ts\"]" \
           --selectProjects '@bdc/neo' \
           --coverage \
           --verbose
}

cov auto-fill-vendor.component

Inside the double quotes, you'll have to escape the literal double quotes.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 chepner