2

This is my scenario, I have a root folder called A, which contains folders B,C,D with n possibilities. Each one of those folders have a bash script. How can I get those bash scripts and run them using bash script.

A/B/run.sh
A/C/run.sh
A/D/run.sh
4
  • do they require any arguments? And does order matter? Commented May 31, 2016 at 16:04
  • order does not matter and they don't require any arguments Commented May 31, 2016 at 16:05
  • 1
    Oops, you forgot to post your code! StackOverflow is about helping people fix their code. It's not a free coding service. Any code is better than no code at all. Meta-code, even, will demonstrate how you're thinking a program should work, even if you don't know how to write it. Commented May 31, 2016 at 16:17
  • Thanks for the note I will do that next time, yeah I didn't even know where to begin with since I didn't have any code yet was struggling to get started. Commented May 31, 2016 at 16:39

2 Answers 2

5

With find :

find . -name *.sh -type f -exec bash -c '[[ -x {} ]] || chmod u+x {}; {}' \;

For each *.sh found :

  • check if file has execute permissions
  • if not set execute permission for user
  • execute script
Sign up to request clarification or add additional context in comments.

2 Comments

This should be the best recursive solution. :-)
I have found bash's globstar feature to be quite a bit faster at finding things recursively than find. YMMV. +1 from me anyway, since this is superior to the embedded ls solution.
3

easy :)

eval "$(ls A/*/run.sh)"

ls will return a list of file with path to your scripts. (you could use find too)

the " " around the $() will make sure the result keeps new lines

eval will execute the returned lines as a script.

Mind you if there are spaces in the names of your script and stuff this can be a brittle solution. But if it looks like what you have shown, that should work fine.

this is output for an example:

 ~/ eval "$(ls */run.sh)"
 I am running and my name is: one/run.sh
 I am running and my name is: two/run.sh

the run.sh scripts are:

 echo "I am running and my name is: $0"

3 Comments

@yetanotherposter : The other solution is more general and you can easily accommodate non-standard directory names in that.
@Rob : This will fail for file say "my_new_line_directory". But yes, this is the most obvious way to do it :-)
I would have thought that a for loop would be the most obvious way yo do it. This solution appears to be an implementation of the very first warning on the bash pitfalls list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.