davide bubz
davide bubz

Reputation: 1329

preserve inline variable with sudo

Hi i'm trying to make something like this to work in bash

$ http=xx sudo echo $http
xx

but i keep getting an empty line, the only thing that works so far is:

$ export http=xx
$ sudo -E echo $http
xx

what i would like to achieve is the ability to inline a variable for the sudo command

i also tried this as suggested here

$ sudo http=xx echo $http

but with no luck, am i missing something?

Upvotes: 4

Views: 1796

Answers (2)

Maurizio Benedetti
Maurizio Benedetti

Reputation: 3577

It looks to me very similar to an already discussed case:

what if you do:

sudo http=xx su root -c 'echo "$http"'

Try to have a look here https://unix.stackexchange.com/questions/202383/how-to-pass-environment-variable-to-sudo-su

Upvotes: -1

Nahuel Fouilleul
Nahuel Fouilleul

Reputation: 19315

The problem with the first command is that http variable expansion happens before it is set.

$ http=xx sudo echo $http

Try instead

$ http=xx sudo -E bash -c 'echo $http'

The syntax is described in man env

   Some have suggested that env is redundant since the same effect is achieved by:

          name=value ... utility [ argument ... ]

Otherwise if the goal is not to affect current shell environment the export and sudo command can be done in a subshell:

$ ( export http=xx ; sudo -E 'echo $http' )

Upvotes: 5

Related Questions