Question

In bash, php/{composer,sismo} expands to php/composer php/sismo. Is there any way to do this with /bin/sh (which I believe is dash), the system shell ? I'm writing git hooks and would like to stay away from bash as long as I can.

Was it helpful?

Solution

You can use printf.

% printf 'str1%s\t' 'str2' 'str3' 'str4'
str1str2    str1str3    str1str4

OTHER TIPS

There doesn't seem to be a way. You will have to use loops to generate these names, perhaps in a function. Or use variables to substitute common parts, maybe with "set -u" to prevent typos.

I see that you prefer dash for performance reasons, however you don't seem to provide any numbers to substantiate your decision. I'd suggest you measure actual performance difference and reevaluate. You might be falling for premature optimization, as well. Consider how much implementation and debugging time you'll save by using Bash vs. possible performance drop.

I really like the printf solution provided by @mikeserv, but I thought I'd provide an example using a loop.

The below would probably be most useful if you wish to execute one command for each expanded string, rather than provide both strings as args to the same command.

for X in composer sismo; do
    echo "php/$X"                   # replace 'echo' with your command
done

You could, however, rewrite it as

ARGS="$(for X in composer sismo; do echo "php/$X"; done)"
echo $ARGS                          # replace 'echo' with your command

Note that $ARGS is unquoted in the above command, and be aware that this means that its content is wordsplitted (i.e. if any your original strings contain spaces, it will break).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top