在Bash中的命令不适用于管道中的第二个命令之前设置环境变量 [英] Setting an environment variable before a command in Bash is not working for the second command in a pipe

查看:89
本文介绍了在Bash中的命令不适用于管道中的第二个命令之前设置环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在给定的外壳中,通常我会设置一个或多个变量,然后运行命令.最近,我了解了在命令前添加变量定义的概念:

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

这可行...有点.当您更改LC_ *变量(这似乎会影响命令,但它的参数,例如'[az]'char范围)时,或者在将输出管道输送到因此,另一个命令:

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

我也可以在somecommand2前面加上"FOO = bar",它可以工作,但是会增加不必要的重复,并且对根据变量解释的参数没有帮助(例如'[az]')

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?

我在考虑以下问题:

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


我有很多好的答案!目标是保持这种单线,最好不使用导出".总体上,使用Bash调用的方法是最好的,尽管括号中带有"export"的版本更为紧凑.使用重定向而不是管道的方法也很有趣.


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.

推荐答案

FOO=bar bash -c 'somecommand someargs | somecommand2'

这篇关于在Bash中的命令不适用于管道中的第二个命令之前设置环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆