Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting an environment variable before a command in Bash is not working for the second command in a pipe

In a given shell, normally I'd set a variable or variables and then run a command. Recently I learned about the concept of prepending a variable definition to a command:

FOO=bar somecommand someargs 

This works... kind of. It doesn't work when you're changing a LC_* variable (which seems to affect the command, but not its arguments, for example, '[a-z]' char ranges) or when piping output to another command thusly:

FOO=bar somecommand someargs | somecommand2  # somecommand2 is unaware of FOO 

I can prepend somecommand2 with "FOO=bar" as well, which works, but which adds unwanted duplication, and it doesn't help with arguments that are interpreted depending on the variable (for example, '[a-z]').

So, what's a good way to do this on a single line?

I'm thinking something on the order of:

FOO=bar (somecommand someargs | somecommand2)  # Doesn't actually work 

I got lots of good answers! The goal is to keep this a one-liner, preferably without using "export". The method using a call to Bash was best overall, though the parenthetical version with "export" in it was a little more compact. The method of using redirection rather than a pipe is interesting as well.

like image 525
MartyMacGyver Avatar asked Jun 01 '12 19:06

MartyMacGyver


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.

How do I set an environment variable for a single command?

We can set variables for a single command using this syntax: VAR1=VALUE1 VAR2=VALUE2 ... Command ARG1 ARG2...

How can you set environment variables from the command line?

To set an environment variable, use the command " export varname=value ", which sets the variable and exports it to the global environment (available to other processes). Enclosed the value with double quotes if it contains spaces. To set a local variable, use the command " varname =value " (or " set varname =value ").

How do you set a variable value in bash?

To create a variable, you just provide a name and value for it. Your variable names should be descriptive and remind you of the value they hold. A variable name cannot start with a number, nor can it contain spaces. It can, however, start with an underscore.


1 Answers

FOO=bar bash -c 'somecommand someargs | somecommand2' 
like image 50
Dennis Williamson Avatar answered Oct 10 '22 16:10

Dennis Williamson