I once made a useful script for a similar purpose, with a function fcd for find-n-cd.
You type fcd foo
and 3 things may happen:
- No such directory foo is found, then it returns with
"no such directory " $1
- One file is found: It tests whether it is a directory (or just a file) and if so, it cds there.
- Multiple files are found - then a selection is presented, where you just type the number of the selection (or a special number for return).
It is similar in that it doesn't need you to type the whole path, but you have call the function explicitly.
#!/bin/bash
#
# find cd. For input foo, find all directories .../.../foo
# GPLv3 Stefan Wagner (2010, 2012)
#
# doesn't handle blanks in directory names gracefully.
#
fcd ()
{
list=$(locate $1 | egrep "/$1$")
count=$(echo $list | wc -w )
case $count in
0)
echo "unknown directory: "$1 && return
# could search for partial matches Doc => Documentation
;;
1)
if [[ -d "$list" ]]; then
echo "$list";
cd "$list";
else
echo "not a directory: $1"
fi
;;
*)
select directory in $list "/exit/"
do
if [[ "$directory" = "/exit/" ]]; then break; fi
if [[ -d "$directory" ]]; then
echo "$directory";
cd "$directory";
break
else
echo "not a directory: "$1
fi
done
;;
esac
}
You have to source
the function (source fcd.sh
| . fcd.sh
) and can't call it as script, because cd
would else only happen in the context of the script, and after finishing you would happen to be back in your starting dir immediately.
Since it works with locate
, it is pretty fast in finding directories (but not always up to date).
It doesn't handle blanks in directory names gracefully. If you have an elegant solution for the problem I would be happy.