diff --git a/bin/ch-run.c b/bin/ch-run.c index c7e3df006..a81643122 100644 --- a/bin/ch-run.c +++ b/bin/ch-run.c @@ -255,8 +255,12 @@ void fix_environment(struct args *args) char *old_value, *new_value; // $HOME: If --home, set to “/home/$USER”. - if (args->c.host_home) + if (args->c.host_home) { Z_ (setenv("HOME", cat("/home/", username), 1)); + } else if (path_exists("/root", NULL, true)) { + Z_ (setenv("HOME", "/root", 1)); + } else + Z_ (setenv("HOME", "/", 1)); // $PATH: Append /bin if not already present. old_value = getenv("PATH"); diff --git a/doc/ch-run.rst b/doc/ch-run.rst index 2e4b24f2e..4353d72f3 100644 --- a/doc/ch-run.rst +++ b/doc/ch-run.rst @@ -317,6 +317,8 @@ Environment variables :code:`ch-run` leaves environment variables unchanged, i.e. the host environment is passed through unaltered, except: +* by default (:code:`--home` not specified), :code:`HOME` is set to + :code:`/root`, if it exists, and :code:`/` otherwise. * limited tweaks to avoid significant guest breakage; * user-set variables via :code:`--set-env`; * user-unset variables via :code:`--unset-env`; and diff --git a/examples/chtest/Build b/examples/chtest/Build index b575c6f27..b55121b82 100755 --- a/examples/chtest/Build +++ b/examples/chtest/Build @@ -125,6 +125,8 @@ chmod 0777 img/maxperms_file mkdir img/maxperms_dir chmod 1777 img/maxperms_dir +# Get rid of “/root” directory, used for “HOME” test in “ch-run_misc.bats”. +rmdir "$img"/root ## Tar it up. diff --git a/test/run/ch-run_misc.bats b/test/run/ch-run_misc.bats index cd7637adf..e7aa0d42d 100644 --- a/test/run/ch-run_misc.bats +++ b/test/run/ch-run_misc.bats @@ -60,6 +60,9 @@ EOF } @test "\$HOME" { + [[ $CH_TEST_BUILDER != 'none' ]] || skip 'image builder required' + LC_ALL=C + scope quick echo "host: $HOME" [[ $HOME ]] @@ -67,10 +70,17 @@ EOF # default: no change # shellcheck disable=SC2016 + run ch-run "${ch_imgdir}"/quick -- /bin/sh -c 'echo $HOME' + echo "$output" + [[ $status -eq 0 ]] + [[ $output = "/root" ]] + + # default: no “/root” + # shellcheck disable=SC2016 run ch-run "$ch_timg" -- /bin/sh -c 'echo $HOME' echo "$output" [[ $status -eq 0 ]] - [[ $output = "$HOME" ]] + [[ $output = "/" ]] # set $HOME if --home # shellcheck disable=SC2016