Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: can we have an option for cd to do a plain chdir()



2022-02-09 09:16:46 -0800, Bart Schaefer:
> I started looking at this myself a while back but couldn't find a way
> to untangle the function dependencies.  They're oddly factored and
> other parts of the shell depend on some of the bits in the middle.
[...]

Thanks, that's the impression I had from glancing at the code.

But then what about the idea of having an option like -r that
bypasses all that and does the simple chdir().

BTW, I've just thought of another way to do the equivalent of a
chdir() reliably on Linux provided you have read access to a
directory:

chdir() { cd /dev/fd/3 3< "$1"; }

Beside adding a "cd -r whatever" that just does a
chdir(whatever), we could add:

- "cd -u 3" which does a fchdir(3)
- sysopen -o path -u fd some/path && cd -u "$fd"
  (or sysopen -pu fd some/path as it's neither a read nor write
  open)
  (with -o nofollow, that can help do some safe directory
  traversal)
- sysopen -@ "$fd" -u otherfd some/path
  for openat()

Being able to do fchdir would allow improvements over the
less reliable:

for dir in $dirs; do
  cd $dir
  do-something
  cd ..
done

Or

for dir in $dirs; do
  pushd $dir
  do-something
  popd
done

Which we could replace with:

savedir() sysopen -po cloexec -u "$1" .
chdir_no_follow() {
  local fd ret
  sysopen -po nofollow -u fd -- "$1" || return
  cd -u "$fd"; ret=$?
  exec {fd}<&-
  return "$ret"
}
savedir || exit
for dir in $dirs; do
  chdir_no_follow $dir && do-something
  cd -u "$fd"
done

What do you think?

-- 
Stephane




Messages sorted by: Reverse Date, Date, Thread, Author