BASH: Another one SmarT CD

How you can do change directory using sed’s regexp and other cool staff?
This post is an explanation of the question.

A bit of theory:
cd is a builtin command, so, it don’t changing a working directory of a parent process and it’s ok.

Well, good news – bash have a command source, which can execute file inside current environment.

Here is the code example of my ~/bin/

#!/bin/bash function x:get_new_dir() { local CURDIR="$(pwd)" local SWITCH="$(sed 's/\//\\\//g' <<<"$1")" local TODIR="$(sed 's/\//\\\//g' <<<"$1")" local NEWDIR="$(sed 's/\('"$SWITCH"'\)\(.*\)$/'"$2"'\2/' <<<"$CURDIR")" if [[ "$NEWDIR" != "$CURDIR" ]]; then if [ -d "$NEWDIR" ]; then local SUBCURDIR="$(sed 's|.*\(/'"$SWITCH"'.*\)$|...\1|' <<<"$CURDIR")" local SUBNEWDIR="$(sed 's|.*\(/'"$2"'.*\)$|...\1|' <<<"$NEWDIR")" echo " $SUBCURDIR -> $SUBNEWDIR" >&2 echo "$NEWDIR" return 0; else echo "Destination folder '$NEWDIR' not found." >&2 fi else echo "New folder is the same as the current." >&2 fi return 1; } if [ -n "$1" -a -n "$2" ]; then __NEWDIR="$(x:get_new_dir "$1" "$2")" [ $? -eq 0 ] && builtin cd "${__NEWDIR}" else printf "usage: %s \n" "$0" >&2 fi unset __NEWDIR unset -f x:get_new_dir

And that’s all!

Actually not, I put an alias into ~/.bashrc:

cat >> ~/.bashrc <EOF alias stcd='. ~/bin/' EOF

to use this tool a bit comfortably, e.g the output:

$ stcd trunk prod .../trunk/base/ -> .../prod/base/

Well, it’s the short folder sequence, but imagine the following:

$ cd ~/projects/repos/reponame/trunk/base/test/simple/ $ # Now you want to look something, e.g. in .../prod/... branch $ # Sure, if you have the same folder tree in prod :) $ cd ../../../../prod/base/test/simple # omfg! I make a typo with dots from time to time, well, it's terrible $ pwd /home/user/projects/repos/reponame/prod/base/test/simple/ $ cd ../ # Now a 'cd -' feature is unavailable $ cd simple/ $ stcd prod trunk # that's much faster .../prod/base/test/simple/ -> .../trunk/base/test/simple/ HH

Leave a Reply

Your email address will not be published. Required fields are marked *