When will Bash give HOME an initial value?

Source: Internet
Author: User

Today, I have no intention of discovering the following:

$ env-i bash-c CD

Bash:line 0:cd:home Not set

$ env-i bash-c ' echo $HOME '

This shows that Bash only inherits the HOME variable from the environment variable and never initializes it itself? In order to confirm this idea, I went through the source code, and found that in fact, in a situation, Bash will actively initialize the HOME variable:

if 1 0 )  Set_home_var ();

From the source, Bash is only possible to assign an initial value to the HOME when the shell is a login shell and not in Posix mode. Then I tried it out:

$ env-i Bash--login-c ' echo $HOME '

Hold the grass, why don't you have a value? Then Google a bit, found 14 years someone reported a bug https://lists.gnu.org/archive/html/bug-bash/2014-01/msg00063.html. After looking at this bug I understand that in Bash, there are three different cases of landing Shell:

/* Non-zero means that this shell is a login shell.   Specifically:   0 = not login shell.   1 = Login Shell from Getty (or equivalent fake off)  -1 = login shell from "--login" (or-l) flag.   */ int 0;

One is that the first character of the No. 0 parameter (specified by the exec* function) that is passed in bash when the parent process starts bash is the case where the--login or-l option is used when Bash starts, and the last is a mixture of the above two expressions login_s The value of the hell variable is 1,-1,-2, but from the source just seen, Bash will initialize the HOME variable only if Login_shell is 1. So let's check again:

$ env-i bash-c ' exec-a-whatever bash-c "echo \ $HOME" '

/home/admin

This command is a bit complicated, with the exec-a option used to specify ARGV[0]. We can also write a C program to verify that:

$ cat A.C

#include <unistd.h>

int main () {

Char *argv[] = {"-whatever", "-C", "Echo $HOME", NULL};

Char *envp[] = {NULL};

Execve ("/bin/bash", argv, ENVP);

}

$ gcc A.c-o A

$./A

/home/admin

When will Bash give HOME an initial value?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.