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

前端 未结 6 1484
故里飘歌
故里飘歌 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:37

    Use env.

    For example, env FOO=BAR command. Note that the environment variables will be restored/unchanged again when command finishes executing.

    Just be careful about about shell substitution happening, i.e. if you want to reference $FOO explicitly on the same command line, you may need to escape it so that your shell interpreter doesn't perform the substitution before it runs env.

    $ export FOO=BAR
    $ env FOO=FUBAR bash -c 'echo $FOO'
    FUBAR
    $ echo $FOO
    BAR
    
    0 讨论(0)
  • 2020-11-27 09:38

    How about exporting the variable, but only inside the subshell?:

    (export FOO=bar && somecommand someargs | somecommand2)
    

    Keith has a point, to unconditionally execute the commands, do this:

    (export FOO=bar; somecommand someargs | somecommand2)
    
    0 讨论(0)
  • 2020-11-27 09:42

    A simple approach is to make use of ;

    For example:

    ENV=prod; ansible-playbook -i inventories/$ENV --extra-vars "env=$ENV"  deauthorize_users.yml --check
    
    0 讨论(0)
  • 2020-11-27 09:44
    FOO=bar bash -c 'somecommand someargs | somecommand2'
    
    0 讨论(0)
  • 2020-11-27 09:45

    Use a shell script:

    #!/bin/bash
    # myscript
    FOO=bar
    somecommand someargs | somecommand2
    
    > ./myscript
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题