How to Fix “Bash Script Execution Error”?

The Bash shell script is the file that comprises the sequence of commands to display the output after execution of the script file. Sometimes when the script is being executed, Linux users face an execution error which occurs when the script is not executable.

This blog will state the reason and the possible solutions to fix the error:

Reason: No Executable Permission

One of the most common reasons is that the script file does not have the required permission to execute it in the terminal. 

Solution 1: Grant the Executable Permission

The script file can be executed to run the file as the program in the terminal, but this file should have the execute permissions. 

Check the File Permission

To find out the script file’s permissions, list its permissions by executing the “ls” command with the “-l” option by specifying the name of the script file as “myfile.sh”:

$ ls -l myfile.sh

In the above output, we can see that the file “myfile.sh” has no executable permissions. 

Make Shell Script Executable

To execute the file executable, users can utilize the “chmod” command with the “+x” utility. For instance, we will make the “myfile.sh” executable:

$ chmod +x myfile.sh

With the execution of the above command, the script file is granted execution permissions which can be verified:

$  ls -l myfile.sh

Verify the Shell Script Executable

Now execute the “myfile.sh” file in the terminal with the “sudo” privileges:

$ sudo ./myfile.sh

The shell script file has been executed, and the output of the file “Welcome to ItsLinuxFoss” is displayed on the screen.

Alternate Solution: Create a New Script File and Execute it

To create a .sh file executable in Linux, users can utilize the “touch” command by specifying the filename with the “.sh extension”. For example, we create a “testFile.sh” script file by executing the below script:

$ touch testFile.sh

Then open the file with the nano text editor and write some commands. Before writing the commands, ensure that you have added “#!/bin/bash” to execute it as a Bash interpreter. And also, at the end of the script, change the file permissions:

#!/bin/bashecho “Welcome to ItsLinuxFoss”chmod u+x testFile.sh

Close the file by saving its content. Then run the file, and it will be executed as the shell script:

$ sudo ./testFile.sh

The output “Welcome to ItsLinuxFoss” has been displayed on the screen.

Conclusion

To make the shell script executable, grant the executable permissions to the file by using the command “chmod +x [filename].sh”. Additionally, users can create a new script file and execute it. This blog has explained possible solutions to make the shell script executable in Linux.