7

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.

zrajm
  • 1,361
  • 1
  • 12
  • 21
greg0ire
  • 22,714
  • 16
  • 72
  • 101

3 Answers3

7

You can use printf.

% printf 'str1%s\t' 'str2' 'str3' 'str4'
str1str2    str1str3    str1str4
mikeserv
  • 694
  • 7
  • 9
4

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.

spbnick
  • 5,025
  • 1
  • 17
  • 22
  • I think it is indeed premature optimization, I was not sure because I don't write that much shell scripts. I realize they don't do anything complicated so the difference will only bash's startup time... – greg0ire Jul 23 '13 at 10:22
  • @greg0ire, yes, mostly the startup time, but it can still be important for your case if you need many script invocations, or use many sub-shells in your code. If performance is important for you, measure it for a typical scenario. – spbnick Jul 23 '13 at 10:30
  • time gives me a difference drop : bash=5ms , sh=3ms . I think it's acceptable though. – greg0ire Jul 23 '13 at 11:33
0

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).

zrajm
  • 1,361
  • 1
  • 12
  • 21