Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting environment variables for multiple commands in bash one-liner

Let's say I have following command

$> MYENVVAR=myfolder echo $MYENVVAR && MYENVVAR=myfolder ls $MYENVVAR

I mean that MYENVVAR=myfolder repeats

Is it possible to set it once for both "&&" separated commands while keeping the command on one line?

like image 733
Pavel K. Avatar asked Dec 24 '12 18:12

Pavel K.


People also ask

How do I set environment variables 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.

Can you have multiple commands on a single line in Linux?

Linux allows you to enter multiple commands at one time. The only requirement is that you separate the commands with a semicolon. Running the combination of commands creates the directory and moves the file in one line.


1 Answers

Assuming you actually need it as an environment variable (even though the example code does not really need an environment variable; some shell variables are not environment variables):

(export MYENVVAR=myfolder; echo $MYENVVAR && ls $MYENVVAR) 

If you don't need it as an environment variable, then:

(MYENVVAR=myfolder; echo $MYENVVAR && ls $MYENVVAR) 

The parentheses create a sub-shell; environment variables (and plain variables) set in the sub-shell do not affect the parent shell. In both commands shown, the variable is set once and then used twice, once by each of the two commands.

like image 124
Jonathan Leffler Avatar answered Oct 12 '22 18:10

Jonathan Leffler