Skip to content
This repository was archived by the owner on Jun 16, 2025. It is now read-only.

Commit 070d365

Browse files
floppymkrader1961
authored andcommitted
Fix expansion of bare tildes when HOME is unset
Use getpwuid to find the user name and home directory. Cache the user name for future logins_tree lookups to avoid repeating the getpwuid call. Fixes: #1391 (cherry picked from commit c4f582d)
1 parent d950075 commit 070d365

File tree

2 files changed

+17
-4
lines changed

2 files changed

+17
-4
lines changed

src/cmd/ksh93/sh/macro.c

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2411,14 +2411,19 @@ static_fn void tilde_expand2(Shell_t *shp, int offset) {
24112411
static_fn char *sh_tilde(Shell_t *shp, const char *string) {
24122412
char *cp;
24132413
int c;
2414-
struct passwd *pw;
2414+
struct passwd *pw = NULL;
24152415
Namval_t *np = NULL;
24162416
static Dt_t *logins_tree;
2417+
static char *username;
24172418

24182419
if (*string++ != '~') return NULL;
24192420
if ((c = *string) == 0) {
2420-
if (!(cp = nv_getval(sh_scoped(shp, HOME)))) cp = getlogin();
2421-
return cp;
2421+
if ((cp = nv_getval(sh_scoped(shp, HOME)))) return cp;
2422+
if (!username) {
2423+
if (!(pw = getpwuid(getuid()))) return NULL;
2424+
if (!(username = strdup(pw->pw_name))) return NULL;
2425+
}
2426+
string = username;
24222427
}
24232428
if ((c == '-' || c == '+') && string[1] == 0) {
24242429
if (c == '+') {
@@ -2490,7 +2495,7 @@ static_fn char *sh_tilde(Shell_t *shp, const char *string) {
24902495
}
24912496
#endif // __CYGWIN__
24922497
if (logins_tree && (np = nv_search(string, logins_tree, 0))) return nv_getval(np);
2493-
if (!(pw = getpwnam(string))) return NULL;
2498+
if (!pw && !(pw = getpwnam(string))) return NULL;
24942499
#if __CYGWIN__
24952500
skip:
24962501
#endif // __CYGWIN__

src/cmd/ksh93/tests/builtins.sh

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -506,6 +506,14 @@ then
506506
rmdir "$pwd/f1"
507507
fi
508508
509+
# =======
510+
# Verify `~` expansion works if `$HOME` is not set.
511+
# Regression test for https://github.com/att/ast/issues/1391
512+
expect="$(print ~$(id -un))"
513+
actual=$(unset HOME; $SHELL -c 'cd /; cd ~; pwd')
514+
[[ $actual == $expect ]] || log_error "bare ~ expansion with unset HOME" "$expect" "$actual"
515+
516+
# =======
509517
TESTDIRSYMLINK="$TEST_DIR/testdirsymlink"
510518
ln -s "$TEST_DIR" "$TEST_DIR/testdirsymlink"
511519

0 commit comments

Comments
 (0)