Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting environment variable in /usr/bin/env hangs process on Linux

While the man for env on Linux seems to indicate that you can set new environment variables before executing a command. Unfortunately, when I set new variables in a file's shebang on Linux systems, the file never executes.

#!/usr/bin/env VAR1=foo bash
echo $VAR1

When I execute this file on a CentOS or Ubuntu machine, it just sits there.

$ ./shell-env.sh
<nothing happens>

What I find particularly bizarre is this works perfectly fine on OS X with BSD env.

$ ./shell-env.sh
foo
$

Is this just a difference between BSD env and Linux env? Why do the man pages for Linux seem to say it should work the same way as on BSD?

P.S. My use case here is to override the PATH variable, so I can try to find a ruby on the system but that's not on the PATH.

Thank you in advance!

like image 535
Arthur Maltson Avatar asked Oct 29 '22 21:10

Arthur Maltson


1 Answers

There's a way to manipulate the environment before executing a Ruby script, without using a wrapper script of some kind, but it's not pretty:

#!/bin/bash
export FOO=bar
exec ruby -x "$0" "$@"

#!ruby
puts ENV['FOO']

This is usually reserved for esoteric situations where you need to manipulate e.g. PATH or LD_LIBRARY_PATH before executing the program, and it needs to be self-contained for some reason. It works for Perl and possibly others too!

like image 185
mwp Avatar answered Nov 15 '22 07:11

mwp