Jakub K.
Jakub K.

Reputation: 63

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 .bashrc. 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'
else
    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"
    else
        cd $found_dir
    fi
fi
}

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 cd the directory is changed succesfully. Any ideas?

Thanks,

Jakub

Upvotes: 2

Views: 1829

Answers (1)

redneb
redneb

Reputation: 23850

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

to

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.

Upvotes: 7

Related Questions