News for hackers. Stuff that matters.
Re:Z – Jump Around by kazinator on Thursday January 18, 2024 @02:13AM (#39038908)
I've used the pushd stuff for 30 years, but this system I just came up with is way more ergonomic.

The dirs command is a poorly considered interface to what should just be a handful of simple variables.

The whole feature is basically mistake, copied from tcsh in order to help tcsh users switch to Bash or something.

pushd with no arguments swaps between the most recent two. That's an important use case and I nailed that requirement with the "cs" alias.

I just added a function to cdlog_pop aliased to pd, which changes to $c1 and removes it, rotating the entries in the other direction. I extended the history to 9 items (with c5 to c9 being hidden entries not shown by cdlog).

  if [ -z "$c1" ] ; then
    c9=
    c8=
    c7=
    c6=
    c5=
    c4=
    c3=
    c2=
  fi

  cdlog_chdir()
  {
    local cur=$PWD

    if command cd "$@" && [ "$PWD" != "$cur" ]; then
      # only if we successfully change to a different
      # directory do the following

      if [ "$cur" == "$c2" ] && [ "$PWD" == "$c1" ] ; then
        # Special case: if we changed to the directory that is second
        # in the cdlog, then just swap between those two.
        c2=$PWD
        c1=$cur
      else
        # Otherwise rotate through all
        c9=$c8
        c8=$c7
        c7=$c6
        c6=$c5
        c5=$c4
        c4=$c3
        c3=$c2
        c2=$c1
        c1=$cur
      fi
    fi
  }

  cdlog_pop()
  {
    if [ -n "$c1" ] && command cd "$c1"; then
      c1=$c2
      c2=$c3
      c3=$c4
      c4=$c5
      c5=$c6
      c6=$c7
      c7=$c8
      c8=$c9
      c9=
    fi
  }

  cdlog()
  {
    # c5 through c9 are hidden
    printf "c1: %s\n" "$c1"
    printf "c2: %s\n" "$c2"
    printf "c3: %s\n" "$c3"
    printf "c4: %s\n" "$c4"
  }

  alias cs='cdlog_chdir "$c1"'
  alias cd='cdlog_chdir -P'
  alias pd='cdlog_pop'

There are no comments on this comment yet.