SuckerForMayhem SuckerForMayhem - 8 months ago 51
Bash Question

With Bash or ZSH is there a way to use a wildcard to execute the same command for each script?

I have a directory with script files, say:

... etc

and would like to execute each script like:

$ ./scripts/ start
$ ./scripts/ start

without needing to know all the script filenames.

Is there a way to append
to them and execute? I've tried tab-completion as it's pretty good in ZSH, using
./scripts/*[TAB] start
with no luck, but I would imagine there's another way to do so, so it outputs:

$ ./scripts/ start ./scripts/ start

Or perhaps some other way to make it easier? I'd like to do so in the Terminal without an alias or function if possible, as these scripts are on a box I SSH to and shouldn't be modifying

Answer Source

Use a simple loop:

for script in scripts/*.sh; do
    "$script" start

There's just one caveat: if there are no such *.sh files, you will get an error. A simple workaround for that is to check if $script is actually a file (and executable):

for script in scripts/*.sh; do
    [ -x "$script" ] && "$script" start

Note that this can be written on a single line, if that's what you're after for:

for script in scripts/*.sh; do [ -x "$script" ] && "$script" start; done