J. Kowalczyk J. Kowalczyk - 22 days ago 4x
Linux Question

Cd inside a Bash FUNCTION

My first question on SO, so apologies if not doing something right!

There are many questions on the internet about using cd inside a script, but my problem is in using cd inside a bash function I put in my

. Its task is to find a file and go to the working directory of the file. In case of multiple files found, I just goes to the first one. Here it is:

fcd() {
cd $PWD
if [ -z "$1" ]; then
echo 'Specify a file name to find'
found_dir=$( find . -name $1 -type f -printf \"%h/\" -quit )
echo $found_dir
if [ -z "$found_dir" ]; then
echo "No file found. Directory was not changed"
cd $found_dir

However, when I use it, the directory is found, but trying to
cd $found_dir
results in the message:

cd: (directory_here): No such file or directory

I've excluded possibility of the path being wrong - by copying the output of
echo $found_dir
and pasting it in front of a
the directory is changed succesfully. Any ideas?




You should not quote the directory in the find command, you should quote it later, when you use the variable. So change the find command from

find . -name $1 -type f -printf \"%h/\" -quit


find . -name "$1" -type f -printf %h -quit

The first command returns the directory path surrounded by quotes, as in "/path/to/dir". So when you try to cd to that directory, cd will think that the quotes are part of the path.

Then adjust the cd to cd "$found_dir" to ensure that cd will not fail if $found_dir contains special characters such as space or a *.

Also note that the cd $PWD is redundant as we are already in that directory. Actually, it might even cause a problem since you are not quoting the variable.