4

I have many shell scripts in a directory starting with letter 'a'. How could I execute all of those shell scripts at a shot? Can we develop any other small script to run this?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255

3 Answers3

10

command line:

for each in path_to_directory/a*.sh ; do bash $each ; done

example:

:~$ ll | grep \.sh
-rw-rw-r--  1 user user      1476 Май 25 16:07 123.sh
-rw-rw-r--  1 user user      1176 Май 25 16:09 222.sh
-rw-rw-r--  1 user user       419 Май 20 14:03 2.sh
-rw-rw-r--  1 user user       191 Май 20 17:50 3.sh
-rw-rw-r--  1 user user         9 Июн  2 11:53 a1.sh
-rw-rw-r--  1 user user         9 Июн  2 11:53 a2.sh

i:~$ cat  q1.sh
echo sadf
:~$ cat  a1.sh
echo 123
:~$ cat  a2.sh
echo 234

:~$ for each in ./a*.sh ; do bash $each ; done
123
234

OR you can use a command line utility called run-parts. This tool can automatically discover multiple scripts or programs in a directory, and run them all.

For example, to run all scripts in /etc whose names start with 'a' and end with '.sh':

$ run-parts --regex '^a.*\.sh$' /etc

With "--test" option, you can print the names of the scripts which would be executed, without actually running them. This is useful for testing purpose

$ run-parts --test ./my_script_directory
malyy
  • 2,177
3
find . -maxdepth 1 -type f -perm /111 -name 'a*' -exec {} \;

or

find . -maxdepth 1 -type f -executable -name 'a*' -exec {} \;

Either of these will find all filenames beginning with a in the current directory (but not subdirectories) with owner, group, or other execution bit(s) set, and try to run them.

I say "try" because the attempt may fail, e.g., if only the owner and group execution bits are set AND you are neither the owner nor a member of the group. In that case, you would have no permission to execute the file.

Another possible failure mode is that it can only execute scripts that can be interpreted by your current shell. so an awk or perl etc script beginning with a won't run - it will fail with syntax errors because they're not shell scripts.


Another method is:

for f in ./a* ; do [ -x "$f" ] && [ ! -d "$f" ] && "$f" ; done

That will execute anything beginning with a that is executable by you (and is NOT a directory), no matter what kind of executable it is - shell script, awk script, perl script, binary, etc.

cas
  • 78,579
0

You can try this-

for i in a*; do file "$i"|grep -q 'script' && ./"$i"; done

Explanation-

  1. for i ... - This is a for loop which will iterate over every item that starts with a.
  2. file "$i"|grep ... file command displays the type of the file. This is necessary because there may be other files or directories starting with 'a'. The grep looks for the word 'script' in the output of file
  3. && ./"$i" ... If the search by grep is successful, it executes the script.