[英]Cd inside a Bash FUNCTION
My first question on SO, so apologies if not doing something right! 我关于SO的第一个问题,如果不做正确的事情就道歉!
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
. 互联网上有很多关于在脚本中使用cd的问题,但我的问题是在我放入
.bashrc
的bash函数中使用cd。 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 $found_dir
导致消息:
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. 我已经排除了路径错误的可能性 - 通过复制
echo $found_dir
的输出并将其粘贴到cd
前面,目录会成功更改。 Any ideas? 有任何想法吗?
Thanks, 谢谢,
Jakub 的Jakub
You should not quote the directory in the find command, you should quote it later, when you use the variable. 您不应该在find命令中引用该目录,以后在使用该变量时应该引用它。 So change the find command from
所以改变find命令
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"
. 第一个命令返回由引号括起的目录路径,如
"/path/to/dir"
。 So when you try to cd
to that directory, cd
will think that the quotes are part of the path. 因此,当您尝试
cd
到该目录时, cd
会认为引号是路径的一部分。
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 *
. 然后将
cd
调整为cd "$found_dir"
以确保如果$found_dir
包含特殊字符(如空格或*
,则cd
不会失败。
Also note that the cd $PWD
is redundant as we are already in that directory. 另请注意,
cd $PWD
是冗余的,因为我们已经在该目录中。 Actually, it might even cause a problem since you are not quoting the variable. 实际上,它甚至可能导致问题,因为您没有引用变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.