diff --git a/bin/sh/cd.c b/bin/sh/cd.c index 82bdda99a066..b7af5ba9c05b 100644 --- a/bin/sh/cd.c +++ b/bin/sh/cd.c @@ -164,8 +164,17 @@ docd(char *dest, int print, int phys) if ((phys || (rc = cdlogical(dest)) < 0) && (rc = cdphysical(dest)) < 0) return (-1); - if (print && iflag && curdir) + if (print && iflag && curdir) { out1fmt("%s\n", curdir); + /* + * Ignore write errors to preserve the invariant that the + * current directory is changed iff the exit status is 0 + * (or 1 if -e was given and the full pathname could not be + * determined). + */ + flushout(out1); + outclearerror(out1); + } return (rc); } diff --git a/bin/sh/sh.1 b/bin/sh/sh.1 index 02298b97b7ac..9163ad16dde4 100644 --- a/bin/sh/sh.1 +++ b/bin/sh/sh.1 @@ -2018,6 +2018,11 @@ to return exit status 1 if the full pathname of the new directory cannot be determined reliably or at all. Normally this is not considered an error, although a warning is printed. +.Pp +If changing the directory fails, the exit status is greater than 1. +If the directory is changed, the exit status is 0, or also 1 if +.Fl e +was given. .It Ic chdir A synonym for the .Ic cd diff --git a/bin/sh/tests/builtins/Makefile b/bin/sh/tests/builtins/Makefile index 620951415c6e..cb69b1358311 100644 --- a/bin/sh/tests/builtins/Makefile +++ b/bin/sh/tests/builtins/Makefile @@ -51,6 +51,7 @@ ${PACKAGE}FILES+= cd6.0 ${PACKAGE}FILES+= cd7.0 ${PACKAGE}FILES+= cd8.0 ${PACKAGE}FILES+= cd9.0 cd9.0.stdout +${PACKAGE}FILES+= cd10.0 ${PACKAGE}FILES+= command1.0 ${PACKAGE}FILES+= command2.0 ${PACKAGE}FILES+= command3.0 diff --git a/bin/sh/tests/builtins/cd10.0 b/bin/sh/tests/builtins/cd10.0 new file mode 100644 index 000000000000..f4b5e0ffca5c --- /dev/null +++ b/bin/sh/tests/builtins/cd10.0 @@ -0,0 +1,6 @@ +# $FreeBSD$ + +# Precondition +(cd /bin) || exit +# Verify write error is ignored. +$SH +m -ic 'CDPATH=/:; cd bin 1