How to run a command block in the main shell?
Depends what you mean by as a whole.
If you only mean send several commands to the shell, and make sure the shell doesn't start running them until you've entered them all, then you can just do:
cmd1; cmd2
Or
cmd1Ctrl+VCtrl+Jcmd2
(or enable bracketed-paste (bind 'set enable-bracketed-paste on'
) and paste the commands from a terminal that supports bracketed paste).
Or:
{
cmd1
cmd2
}
To have them on several lines.
If you want to group them so they share the same stdin or stdout for instance, you could use:
{ cmd1; cmd2; } < in > out
Or
eval 'cmd1; cmd2' < in > out
If you want them to run with their own variable and option scope, as bash
doesn't have the equivalent of zsh
anonymous functions, you'd need to define a temporary function:
f() { local var; var=foo; bar;}; f
Instead of ( something )
, which launches something
in a subshell, use { something ; }
, which launches something
in the current shell
You need spaces after the {
, and should also have a ;
(or a newline) before the }
.
Ex:
$ { echo "hello $BASHPID";sleep 5;echo "hello again $BASHPID" ; }
hello 3536
hello again 3536
Please note however that if you launch some complex commands (or piped commands), those will be in a subshell most of the time anyway.
And the "portable" way to get your current shell's pid is $$
.
So I'd instead write your test as:
{ echo "hello $$"; sleep 5 ; echo "hello again $$" ; }
(the sleep is not really useful anyway here)