6

A. { echo "Hello World"; } >outputfile

B. ( echo "Hello World" ) >outputfile

C. ./anothershell.sh

D. /bin/echo "Hello World"

Which is right? And what kind of command can run in the same process of the current shell?

  • I think both A and B – Milind Dumbare Mar 13 '15 at 9:41
  • But hard to prove it. The command echo ends quickly and difficult to catch its process – H Han Mar 13 '15 at 9:47
  • 3
    Additionally, E. . ./anothershell.sh would execute in the current shell. – glenn jackman Mar 13 '15 at 10:29
10

You have asked a couple times about how to prove it. You use environment variable setting as a probe:

export testvar=nope
{ echo "Hello World"; export testvar=yep; } >outputfile
printenv testvar

writes yep

export testvar=nope
( echo "Hello World"; export testvar=yep; ) >outputfile
printenv testvar

writes nope

You'll need to edit your script in (C) and compile a modified echo for (D), but then the corresponding constructs for them will also write nope. This shows explicitly that only case (A) and glennjackman's case (E) from the comments run in the same process.

14

Only A will run within the process of the current shell.

B will run in a subshell because you asked for a subshell by using paranehteses.

C and D will both run outside of the current shell process because they are invocations of external commands.

  • Do you have a way to verify this? – Milind Dumbare Mar 13 '15 at 10:21
  • 1
  • 2
    @Miline you could use strace under Linux or truss under Solaris, for example. Why? Did you expect a different answer? – Celada Mar 13 '15 at 11:19
  • I was just curious to find a way to verify it. – Milind Dumbare Mar 13 '15 at 11:44
  • 2
    @HHan You need to attach strace to the original shell. You could put all the lines in a script and then strace a shell running the script, or attach strace to your running shell with strace -p from a separate terminal. – Random832 Mar 13 '15 at 13:15
4

One distinction you may be missing is that B will fork (so it's another process), but it doesn't actually exec (it's a copy of the same shell, it doesn't go and find /bin/sh and re-run initializers etc). And there are special rules ($$ is the pid of the original shell, for example).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.