Le Tue, Feb 10, 2026 at 12:58:17AM +0700, Robert Elz a écrit :
>     Date:        Mon, 9 Feb 2026 12:04:29 -0500
>     From:        Greg Wooledge <[email protected]>
>     Message-ID:  <[email protected]>
> 
>   | You could implement this yourself with a function.
> 
> Yes, that is absolutely the right way.
I think so!

>   | I would suggest not overriding the "cd" name
> ...
> willing to limit the parameter to a single digit (no cd -11).
Not sure to understand this limitation.

...
>   | up() {
>   |     local i
>   |     for ((i=0; i < $1; i++)); do cd .. || return 1; done
>   | }
> 
> But that's absolutely the wrong way to do it (and not just because
> it is using a bashism that isn't needed for this).

Why not using bashism when creating a bash function! Mostly
intended to be added in .bashrc, in order to improve personal
user's bash interactions!

> The issue is that if, somewhere between the first and last "cd .."
> one of them fails, that function will correctly report something
> like
>       cd .. permission denied
> 
> but then the current directory is who knows where.  How many cd ..'s
> worked before the one that failed.

Another good reason to avoid conscecutive ``cd'' in the function
is to preseve usage of "$OLDPWD"

So my purpose, (with lot of bashisms):

cd() { 
    [[ ${1::1} == - ]] &&
         case ${1:1} in 
            '' | *[^0-9]*) ;;
            *)
                local _cd_upDir
                printf -v _cd_upDir '%*s' ${1:1}
                eval builtin cd ${_cd_upDir// /..\/}
                return $?
                ;;
         esac
    builtin cd "$@"
}

This use no getopt, so `-NNN` should be the first argument!

:~$ cd /var/log/journal/7b6372c63b8a6bb16b47df3f51b776a5
:/var/log/journal/7b6372c63b8a6bb16b47df3f51b776a5$ cd -3
:/var$ cd -
/var/log/journal/7b6372c63b8a6bb16b47df3f51b776a5
:/var/log/journal/7b6372c63b8a6bb16b47df3f51b776a5$ cd -4
:/$ cd
:~$

> And it either works as requested, or it doesn't, in which case $PWD is
> unaltered, you remain in the directory where you started.

Yes, this is a notable third reason!

-- 
 Félix Hauri  -  <[email protected]>  -  http://www.f-hauri.ch

Reply via email to