Shell – Why is #!/usr/bin/env bash not working on the system

environment-variablesshebangshell-script

I ran into some issues when running some installation scripts where they complained of bad interpreter.

So I made a trivial example but I can't figure out what the problem is, see below.

#!/usr/bin/env bash
echo "hello"

Executing the script above results in the following error

[root@ech-10-24-130-154 dc-user]# ./junk.sh
bash: ./junk.sh: /usr/bin/env: bad interpreter: No such file or directory

The /usr/bin/env file exists, see below:

[root@ech-10-24-130-154 dc-user]# ls -l /usr/bin/env
lrwxrwxrwx 1 root root 13 Jan 27 04:14 /usr/bin/env -> ../../bin/env
[root@ech-10-24-130-154 dc-user]# ls -l /bin/env
-rwxr-xr-x 1 root root 23832 Jul 16  2014 /bin/env
[root@ech-10-24-130-154 dc-user]#

If I alter the script to use the regular shebang #!/bin/bash it works no problem. #!/bin/env bash works as well.

What is missing from the environment to allow the portable shebang to work?

ls -lL /usr/bin/env returns ls: cannot access /usr/bin/env: No such file or directory so I guess I need to alter the symbolic link? Can I point it to /bin/env?

env --version is 8.4 and the OS is Red Hat Enterprise Linux Server release 6.6.

Best Answer

ls -lL /usr/bin/env shows that the symbolic link is broken. That explains why the shebang line isn't working: the kernel is trying, and obviously failing, to execute a dangling symbolic link.

/usr/bin/env -> ../../bin/env is correct if /usr and /usr/bin are both actual directories (not symlinks). Evidently this isn't the case on your machine. Maybe /usr is a symbolic link? (Evidently it isn't a symbolic link to /, otherwise /usr/bin/env would be the same file as /bin/env, not a symbolic link).

You need to fix that symbolic link. You can make it an absolute link:

sudo ln -snf /bin/env /usr/bin/env

You can make it a relative link, but if you do, make sure it's correct. Switch to /usr/bin and run ls -l relative/path/to/bin/env to confirm that you've got it right before creating the symlink.

This isn't a default RHEL setup, so you must have modified something locally. Try to find out what you did and whether that could have caused other similar problems.

Related Question