How to execute the output of a command within the current shell?

前端 未结 9 1157
渐次进展
渐次进展 2020-12-04 07:37

I\'m well aware of the source (aka .) utility, which will take the contents from a file and execute them within the current shell.

Now, I\'

相关标签:
9条回答
  • 2020-12-04 07:57

    Try using process substitution, which replaces output of a command with a temporary file which can then be sourced:

    source <(echo id)
    
    0 讨论(0)
  • 2020-12-04 08:03

    Wow, I know this is an old question, but I've found myself with the same exact problem recently (that's how I got here).

    Anyway - I don't like the source /dev/stdin answer, but I think I found a better one. It's deceptively simple actually:

    echo ls -la | xargs xargs
    

    Nice, right? Actually, this still doesn't do what you want, because if you have multiple lines it will concat them into a single command instead of running each command separately. So the solution I found is:

    ls | ... | xargs -L 1 xargs
    

    the -L 1 option means you use (at most) 1 line per command execution. Note: if your line ends with a trailing space, it will be concatenated with the next line! So make sure each line ends with a non-space.

    Finally, you can do

    ls | ... | xargs -L 1 xargs -t
    

    to see what commands are executed (-t is verbose).

    Hope someone reads this!

    0 讨论(0)
  • 2020-12-04 08:03
    `ls | sed ...`
    

    I sort of feel like ls | sed ... | source - would be prettier, but unfortunately source doesn't understand - to mean stdin.

    0 讨论(0)
  • 2020-12-04 08:14

    I think your solution is command substitution with backticks: http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_03_04.html

    See section 3.4.5

    0 讨论(0)
  • 2020-12-04 08:15
    $ ls | sed ... | source /dev/stdin
    

    UPDATE: This works in bash 4.0, as well as tcsh, and dash (if you change source to .). Apparently this was buggy in bash 3.2. From the bash 4.0 release notes:

    Fixed a bug that caused `.' to fail to read and execute commands from non-regular files such as devices or named pipes.

    0 讨论(0)
  • 2020-12-04 08:16

    The eval command exists for this very purpose.

    eval "$( ls | sed... )"
    

    More from the bash manual:

    eval

              eval [arguments]
    

    The arguments are concatenated together into a single command, which is then read and executed, and its exit status returned as the exit status of eval. If there are no arguments or only empty arguments, the return status is zero.

    0 讨论(0)
提交回复
热议问题