January 09, 2013

A bashism a week: brace expansion

Brace expansion is well known and handy, but sadly it is not required by POSIX:2001. Shells that don't support it will simply and silently leave it as is.

If you use it to shorten commands, as in "echo Debian GNU/{Linux,kFreeBSD}", you have to spell it out or use some sort of loop.

When using brace expansion for sequences you will usually have to fall back to using the seq command or using loops. "{1..9}" can be replaced with "seq -s ' ' 1 9", "{1..9..2}" to "seq -s ' ' 1 2 9", and so on.
If you use brace expansion for sequences of characters then seq won't be of much help.

I must note that the seq command is not required by POSIX:2001, however.

Remember, if you rely on any non-standard behaviour or feature make sure you document it and, if feasible, check for it at run-time.

2 comments:

  1. It must be noted that seq is a GNU utility. On the BSDs, the https://www.mirbsd.org/man1/jot utility serves similar purposes, although the syntax differs and the functionalities do not overlap 100%.

    mksh of course handles brace expansion, but it’s a run-time option, and it’s actually turned *off* if invoked as /bin/sh (on Debian) for improved compatibility: I’ve seen #!/bin/sh scripts that *break* if brace expansion is available; most visible example is NetBSD®’s top-level build.sh script.

    //mirabilos, who hopes to be able to drop printf soon…

    ReplyDelete
    Replies
    1. Right, on the BSDs there is usually no "seq" command. FreeBSD 9.0 does provide one, however.

      Delete