bash cd 路径包含空格的问题:“参数太多”

bash cd 路径包含空格的问题:“参数太多”

我创建了一个带有空格的路径,当我尝试更改目录时,尽管转义了空格或引用了路径,但我收到了“参数太多”错误消息:

这是我所做的测试:

# creating a path with spaces in it
$mkdir -p "01.Silly Path/0.2 With Plenty of /0.3 spaces"

# Trying to cd
$cd 01.Silly\ Path/0.2\ With\ Plenty\ of\ /0.3\ spaces/
bash: cd: too many arguments

# Trying with sh
$sh
$ cd 01.Silly\ Path/0.2\ With\ Plenty\ of\ /0.3\ spaces/
$ pwd
/xxx/Documents/dev/01.Silly Path/0.2 With Plenty of /0.3 spaces

# Trying to create a file using the problematic path : it works
$echo "dummy file test" > 01.Silly\ Path/0.2\ With\ Plenty\ of\ /0.3\ spaces/dummy_file.t
$cat 01.Silly\ Path/0.2\ With\ Plenty\ of\ /0.3\ spaces/dummy_file.t
dummy file test

# But command cd fails
$cd 01.Silly\ Path/0.2\ With\ Plenty\ of\ /0.3\ spaces/
bash: cd: too many arguments

$bash --version
GNU bash, version 5.2.15(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2022 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
lde@ldedebian ~/Documents/dev  $
$

# Tried quoting instead of escaping : still having failure with bash
$( cd "01.Silly Path/0.2 With Plenty of /0.3 spaces/" ; pwd)
bash: cd: too many arguments

# But works fine in zsh and sh
$sh -c ' cd "01.Silly Path/0.2 With Plenty of /0.3 spaces/" ; pwd '
/home/xxx/Documents/dev/01.Silly Path/0.2 With Plenty of /0.3 spaces
$zsh -c ' cd "01.Silly Path/0.2 With Plenty of /0.3 spaces/" ; pwd '
/home/xxx/Documents/dev/01.Silly Path/0.2 With Plenty of /0.3 spaces

# And the issue seems to be related to spaces indeed
$mkdir -p "01.Silly_Path/0.2_With_Plenty_of_/0.3_spaces"
$( cd 01.Silly_Path/0.2_With_Plenty_of_/0.3_spaces/; pwd)
/home/xxx/Documents/dev/01.Silly_Path/0.2_With_Plenty_of_/0.3_spaces

我是否错过了有关 Bash 和 space 的某些内容,或者这是一个错误?

答案1

你确认了在评论中cd您安装了一些软件,这些软件使用自己的 shell 功能使shell 的内置实用程序超载。该 shell 函数包含一个漏洞,这使得它在空格上分割其路径名参数(可能是由于忘记双引号变量扩展),导致您观察到的问题。

卸载该软件,或者至少删除 shell 功能

unset -f cd

...可能会解决这个问题。

\$*您还可以选择通过更改为\"\$@\"$*来纠正问题"$@" 在这个文件中

相关内容