2

What method does the login shell use to read /etc/profile?

  • 7
    What do you mean by "method"? Are you asking if it is sourced or executed? – terdon May 14 '17 at 13:35
  • What method does the login shell use to read /etc/profile and $HOME/.bash_profile child process or “source”? this is the whole question on the book. @terdon – Ms.Sahin May 14 '17 at 13:38
  • See github.com/mirror/busybox/blob/master/shell/ash.c#L13519 for how it's done in busybox. – phk May 14 '17 at 20:21
  • 1
    Asking exactly the same question three times (in the title, in the body question, and in the comments) doesn't make it any clearer. – roaima May 14 '17 at 21:03
10

It is sourced. The difference between executing and sourcing is explained in this post. The important difference here is that sourcing causes the commands in the sourced file to be run in the current shell. That means that any variables defined in the file will now be available in the shell. To illustrate the difference, try the following:

$ cat foo        ## a simple file with a variable definition
var="hello"
$ chmod +x foo   ## make file executable
$ ./foo          ## execute
$ echo "$var"    ## var is not set in the parent shell

$ . foo          ## source
$ echo "$var"    ## var is now set in the parent shell
hello

So, since /etc/profile needs to be able to affect the shell it was read from, it is sourced and not executed.

  • 3
    I think it's better to say source foo for the example instead of . foo, since 1) space might be not as visible between . and foo, 2) source is much more suitable for search in the man page than .. In a comment then it'd be possible to say that . foo is another way to say this. – Ruslan May 14 '17 at 16:15
  • 6
    @Ruslan source isn't portable, it's just an alias to the . command in a few shells. The portable way is . so I prefer to use the shell-agnostic command here. – terdon May 14 '17 at 16:50
4

The shell sources those files.

Doing it in a child process would mean that the shell would not have the variables etc. set in its own environment as they would be set in the child process' environment (these are separate). A child process may not pass its environment back to the parent.

See also: How to make a variable from a subshell available in the parent shell

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.