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

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

问题描述

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

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]' 字符范围)或将输出通过管道传输到另一个命令因此:

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天全站免登陆