How to find and run a bash script?

27,099

Solution 1

  1. Use the find command for it in your home:

    find ~ -name script.sh 
    
  2. If you didn't find anything with the above, then use the find command for it on the whole F/S:

    find / -name script.sh 2>/dev/null
    

    (2>/dev/null will avoid unnecessary errors to be displayed) .

  3. Launch it:

    /<whatever_the_path_was>/script.sh
    

And all at once would give; more on how to find and exec:

find / -name "script.sh" -exec chmod +x {} \; -exec {} \; 2>/dev/null 

(beware if you have more than one "script.sh", it will run them all)

Solution 2

There may be several scripts called exactly the same thing on your file system, so locating it based on the name and then blindly executing it is probably a very bad idea.

To locate it, use find as shown by J. Chomel in another answer to your question, or use locate:

$ locate script.sh

This will find all files called script.sh in locations that are readable by all users based on a database search on your system. Note that the database is updated on a regular basis (once daily or once weekly, depending on how it's configured), so files added since the last file system scan will not be found, but it's a lot faster than find.

You could use select to generate a menu from which you could select the correct script and execute it:

$ select script in $( locate script.sh ); do echo "$script"; break; done

Change echo to command to actually run the script you've selected rather than just printing its name.

Share:
27,099

Related videos on Youtube

Pythoncoder
Author by

Pythoncoder

Updated on September 18, 2022

Comments

  • Pythoncoder
    Pythoncoder almost 2 years

    I have a script named script.sh. I don't know where it is in the file system, but I do know it exists.

    How do I find the script, make it executable, and run it all in one line through the command line?

    I would like to run it with a single command. Find, make executable and execute.

  • Pythoncoder
    Pythoncoder over 7 years
    I would like to run it with a single command. Find, make executable and execute.
  • Rakesh Sharma
    Rakesh Sharma over 7 years
    find . -name script.sh -type f -exec bash {} \; otherwise if you wanted to make if executable first then find . -name script.sh -type f -exec chmod +x {} \; -exec {} \;