Why would one run cat|bash before copying/pasting into a terminal?

。_饼干妹妹 提交于 2021-02-11 12:22:28

问题


I've seen someone running cat|bash before pasting commands from the clipboard into a terminal.

bash executes commands in bash I do not know why do we need cat here and |(pipe).

What useful effects does this practice have?


回答1:


It was my colleague who executed a bunch of command in the terminal, [...] he did cat|bash before pasting those set of commands

He likely this to stop Bash from interpreting anything in the commands as editing input, to override any special keybindings and aliases he's set up, and/or to prevent commands from consuming the command stream as input.

Consider this command with two embedded tab characters:

    if true
    then
        echo "yup"
    fi

Here's what happens when you paste it into a shell (because the tab characters trigger tab completion in interactive input):

$ if true
> then
>
Display all 2600 possibilities? (y or n)
!                                   grub-mkfont                         pnmmontage
./                                  grub-mkimage                        pnmnlfilt
:                                   grub-mklayout                       pnmnoraw

And here's a snippet that involves ssh:

ssh localhost uptime
echo "Finished"

When you paste it into a shell, the second command gets consumed as input by ssh, so you get this:

$ ssh localhost uptime
 09:53:40 up 28 days, 18:33, 25 users,  load average: 0.06, 0.01, 0.00

In both cases, pasting into cat | bash instead will cause the commands to run as-is.




回答2:


This reads commands from the terminal and executes them in bash. It's similar to just running bash by itself, except that when bash's standard input is a terminal it runs interactively by default -- it displays prompts, performs input editing, enable aliases, performs job control, etc. This will run non-interactively, so it will just execute the commands as if they were in a script.

I'm not sure why someone would want to do this.




回答3:


In addition to the other good answers given here (tab completion, ssh/ptty), cat|bash will not let the pasted commands change the environment of the current shell.

For example, if the copy-n-paste'd commands are:

PATH=/some/place/odd:$PATH
somecommand some args

The the PATH is unchanged after the shell in cat|bash exits after running somecommand.



来源:https://stackoverflow.com/questions/59901154/why-would-one-run-catbash-before-copying-pasting-into-a-terminal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!