Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define environment variable in input command of su

Tags:

bash

shell

su

This command has an empty output.

su user -c "ABC=abc;echo $ABC"

Any idea, how can I define a variable in the input command?

like image 921
Attila Zobolyak Avatar asked Sep 09 '10 12:09

Attila Zobolyak


People also ask

How do I set an environment variable in terminal?

To set (or change) a environment variable, use command " set varname=value ". There shall be no spaces before and after the '=' sign. To unset an environment variable, use " set varname= ", i.e., set it to an empty string.

How do I set environment variables?

On the Windows taskbar, right-click the Windows icon and select System. In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables. Click New to create a new environment variable.

How do I reference an environment variable in bash?

The easiest way to set environment variables in Bash is to use the “export” keyword followed by the variable name, an equal sign and the value to be assigned to the environment variable.

Which command can create environment variable?

The export command is used to set Environment variables. Environment Variables created in this way are available only in the current session.


2 Answers

Change your quotes to single quotes. The double quotes allow the variable to be substituted in the current environment where it's not set yet. To see the difference, try your version with $USER and compare it to this one:

su user -c 'ABC=abc; echo $ABC; echo $USER'
like image 83
Dennis Williamson Avatar answered Oct 11 '22 03:10

Dennis Williamson


If using a bourne shell variant:

ABC=abc su user -c 'echo $ABC'

If not, use env.

env ABC=abc su user -c 'echo $ABC'
like image 41
William Pursell Avatar answered Oct 11 '22 02:10

William Pursell