NHẤT PHƯƠNG PHÁP
Yêu cầu: không có gì (n.b., Đây là kỹ thuật tương tự như getent mà không đòi hỏi getent)
home() { # returns empty string on invalid user
grep "^$1:" /etc/passwd | cut -d ':' -f 6
}
# grep "^$user:" /etc/passwd | cut -d ':' -f 6
/var/lib/memcached
PHƯƠNG PHÁP tốt đẹp cho ROOT LINUX
Yêu cầu: Linux, gốc (hoặc sudo)
home() { # returns errorlevel 1 on invalid user
su "$1" -s '/bin/sh' -c 'echo $HOME'
}
# su memcached -s '/bin/sh' -c 'echo $HOME'
/var/lib/memcached
GIẢI PHÁP ĐỂ MỞ RỘNG COMPLETE
magic() { # returns unexpanded tilde express on invalid user
local _safe_path; printf -v _safe_path "%q" "$1"
eval "ln -sf $_safe_path /tmp/realpath.$$"
readlink /tmp/realpath.$$
rm -f /tmp/realpath.$$
}
Ví dụ sử dụng:
$ magic ~nobody/would/look/here
/var/empty/would/look/here
$ magic ~invalid/this/will/not/expand
~invalid/this/will/not/expand
PHƯƠNG PHÁP CHO Tận CSH
Đây là một kịch bản BASH, nó chỉ gọi csh.
Yêu cầu: csh
home() { # return errorlevel 1 on invalid user
export user=$1; csh -c "echo ~$user"
}
$ export user=root; csh -c "echo ~$user"
/var/root
$ export user=nodfsv; csh -c "echo ~$user"
Unknown user: nodfsv.
PHƯƠNG PHÁP của sự tuyệt vọng
Yêu cầu: ngón tay (phản đối)
home() {
finger -m "$1" |
grep "^Directory:" |
sed -e 's/^Directory: //' -e 's/ .*//'
}
# finger -m "haldaemon" |
> grep "^Directory:" |
> sed -e 's/^Directory: //' -e 's/ .*//'
/home/haldaemon
Bạn có thể kết hợp các grep hoạt động vào sed, nhưng vì phương pháp này là sucky, tôi sẽ không bận tâm.
Điều này sẽ không thành công nếu ví dụ: LDAP auth được sử dụng. –
Bạn muốn sử dụng 'getent passwd'. Điều đó sẽ sử dụng bất kỳ cơ sở dữ liệu Name Service Switch nào được cấu hình trong /etc/nsswitch.conf (ví dụ:/etc/passwd, nis, ldap, v.v.). –