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
if [ -z "$1" ]; then
echo 'Specify a file name to find'
found_dir=$( find . -name $1 -type f -printf \"%h/\" -quit )
if [ -z "$found_dir" ]; then
echo "No file found. Directory was not changed"
cd: (directory_here): No such file or directory
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 "$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.