【问题标题】:How do you pass a directory with whitespace into a function as an argument?如何将带有空格的目录作为参数传递给函数?
【发布时间】:2019-07-18 08:34:53
【问题描述】:

我正在编写一个 shell 脚本,它将通过使用一个函数多次导航到我计算机上的指定目录,并且指定的目录之一有两个单词,因此包含空格。

我已将cd "$1".. 用于传入的参数。我也尝试过cd "$@" 并实际上将变量替换为用引号括起来的实际目录名称,但错误仍然存​​在。

function Navigate()
{

    cd ~
    cd "$1"
    cd "$2"
    cd "$3"
    open $PWD

}

Navigate "Directory1" "Directory2" "Directory3"

我不断收到一条错误消息,显示找不到目录。

例子:如果第二个目录被命名为test directory,错误信息会显示:

/Users/Name/Directory1/test 和 /Users/Name/Directory1/test Directory/Directory3/Directory3 不存在

【问题讨论】:

  • an error message that is showing 请发布确切的错误消息。
  • open "$PWD"
  • 听起来你叫Navigate dir1 test directory dir2而不是Navigate dir1 "test directory" dir3

标签: bash macos terminal


【解决方案1】:
function Navigate()
{

    cd ~
    cd "$1"
    cd "$2"
    cd "$3"
    open "$PWD"

}

如上所示在$PWD 周围加上引号,它会正常工作。

当您说open $PWD 时,它会扩展为open first_word_of_dir_name second_word_of_dir_name。这会导致open 得到两个参数,都是无效的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    • 2010-10-03
    • 2013-01-27
    • 2011-10-04
    • 2017-11-25
    相关资源
    最近更新 更多