Http Hobo

Another blog with web-development tips’n’tricks. | About me

2 posts tagged

unix

Script execution exit code is 126, but permissions are good

I have PHP script which calls bash script using exec() function. Worked well until recent release. When I checked logs, I found that the script is now exiting with code 126.

Documentation says that exit code 126 is reserved and it means that command cannot be executed. Comment elaborates, that this is permission problem or command is not an executable. Besides that I googled the problem, and most of the comments over the Internet is that it’s about permissions. Said that, it’s not surprising that my eyes caught only first part of the comment about permissions.

We checked script permissions – they were totally ok. Then I found out that parent directories’ permissions also matter, checked them – also all good. Then checked permissions of a binary being called by our script – good too.

When we tried to execute the script from CLI, we’ve got the following error:

-bash: path/to/script.sh: /bin/bash^M: bad interpreter: No such file or directory

You see ^M? That’s our guy. ^M is also known as CR or \r – Windows line-ending. When it’s somewhere in the script it usually doesn’t cause problems. But it’s presence in shebang could not be excused, so we’ve got exit code 126. That’s that part of the documentation saying “command is not an executable”.

If you get exit code 126 and permissions look good, check line endings.

2017   unix

Ensuring executed script’s parent directories permissions in Unix-like systems

I’ve recently discovered that it’s not sufficient enough to grant +x permission to a script in order to make it executable. Besides that you have to check if script’s parent directories also have execution rights. But it depends on how you call the script.

If you use absolute path, than all the parent directories up to the one in root folder will be checked for having execution rights.

; If you execute the following script, directories "path", "to" and "my" should have execution rights
/path/to/my/script.sh

If you use relative path, than you should grant execution rights to all the directories mentioned in the script’s path. Actually this rule applied to absolute path too.

; Here execution rights are checked for "to" and "my" directories only
cd /path
to/my/script.sh

; This scenario is the same as absolute path - .. refers to "path" folder, so it need to have execution rights here as well
cd /path
../to/my/script.sh

So, summarizing it I would put the rule here again.

If a script is being executed in Unix-like system, all the parent directories mentioned in the script path have to have execution rights.

2017   unix