When I was trying to run all scripts in a directory using run-parts command, I encountered with an error - "run-parts: failed to exec script.sh: Exec format error". The scripts worked just fine when I directly execute them like "./script.sh" and "sh script.sh". But they didn't work when I ran them with run-parts command. For those wondering, the run-parts command will run all scripts in a directory. If you got an error like this while running a script, this quick tip will help you to fix "Exec format error" when running scripts with run-parts command in Linux.
Fix "Exec format error" When Running Scripts With run-parts Command
To run all scripts in the Documents folder, I ran:
$ run-parts --regex '^s.*\.sh$' Documents
I got the following error message:
run-parts: failed to exec Documents/script1.sh: Exec format error run-parts: Documents/script1.sh exited with return code 1 run-parts: failed to exec Documents/script2.sh: Exec format error run-parts: Documents/script2.sh exited with return code 1 run-parts: failed to exec Documents/script3.sh: Exec format error run-parts: Documents/script3.sh exited with return code 1 run-parts: failed to exec Documents/script4.sh: Exec format error run-parts: Documents/script4.sh exited with return code 1
To fix "Exec format error", you need to add a shebang at the start of your scripts so the kernel will know how to run them. For those wondering, a shebang is the character sequence consisting of the characters number sign and exclamation mark (#!) at the beginning of a script. When you add the shebang at the start of a text file, it is interpreted as an executable file.
Most scripts starts with a shebang. Here are some typical shebang examples.
Bourne shell, or a compatible shell:
This is what we call a shebang.
Now, let us get back to the topic. Edit your scripts using your favorite editor:
$ nano Documents/ostechnix.sh
Add the following shebang at the beginning of the script:
Now you can be able to run the scripts with run-parts command without any issues using run-parts command.
As one of our reader Mr.Danesh mentioned in the comment section below, Instead of hard-coding the path of the interpreter, e.g.
We can use:
This is more portable in case the interpreter is installed in some other (non-default) directory. env is a shell command for Unix and Unix-like operating systems. It is often used by shell scripts to launch the correct interpreter.
You can also use ShellCheck utility to find problems in your shell scripts.
Hope this helps.