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

前端 未结 6 1497
故里飘歌
故里飘歌 2020-11-27 08:54

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:

6条回答
  •  北海茫月
    2020-11-27 09:58

    You can also use eval:

    FOO=bar eval 'somecommand someargs | somecommand2'
    

    Since this answer with eval doesn't seem to please everyone, let me clarify something: when used as written, with the single quotes, it is perfectly safe. It is good as it will not launch an external process (like the accepted answer) nor will it execute the commands in an extra subshell (like the other answer).

    As we get a few regular views, it's probably good to give an alternative to eval that will please everyone, and has all the benefits (and perhaps even more!) of this quick eval “trick”. Just use a function! Define a function with all your commands:

    mypipe() {
        somecommand someargs | somecommand2
    }
    

    and execute it with your environment variables like this:

    FOO=bar mypipe
    

提交回复
热议问题