SuckerForMayhem SuckerForMayhem - 3 days ago 6
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:

scripts/
foo.sh
script1.sh
test.sh
... etc


and would like to execute each script like:

$ ./scripts/foo.sh start
$ ./scripts/script1.sh start
etc


without needing to know all the script filenames.

Is there a way to append
start
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/foo.sh start ./scripts/script1.sh 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
*._profile
or
.*rc
files.

Answer

Use a simple loop:

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

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
done

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
Comments