简体   繁体   English

如何将带有空格的目录作为参数传递给函数?

[英]How do you pass a directory with whitespace into a function as an argument?

I am writing a shell script that will navigate to a specified directory on my computer multiple times through the use of a function, and one of the directories that is specified has two words, and therefore contains whitespace. 我正在编写一个Shell脚本,该脚本将通过使用一个功能多次导航到计算机上的指定目录,并且指定的目录之一包含两个单词,因此包含空格。

I have used cd "$1".. for the arguments passed in. I have also tried cd "$@" and actually replacing the variable with the actual directory name surrounded by quotes, and the error persists. 我使用cd "$1"..作为传入的参数。我也尝试过cd "$@" ,实际上用实际的目录名称(用引号引起来)替换了变量,错误仍然存​​在。

function Navigate()
{

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

}

Navigate "Directory1" "Directory2" "Directory3"

I keep getting an error message that is showing that the directory can not be found. 我不断收到一条错误消息,显示找不到目录。

Example: If the 2nd directory was named test directory , the error message would show: 示例:如果第二个目录名为test directory ,则错误消息将显示:

/Users/Name/Directory1/test and /Users/Name/Directory1/test Directory/Directory3/Directory3 do not exist / Users / Name / Directory1 / test和/ Users / Name / Directory1 / test Directory / Directory3 / Directory3不存在

function Navigate()
{

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

}

Put quotes around $PWD as shown above and it will work just fine. 如上所示,在$PWD周围加上引号,它将很好用。

When you say open $PWD , it expands into open first_word_of_dir_name second_word_of_dir_name . 当您说open $PWD ,它将扩展为open first_word_of_dir_name second_word_of_dir_name This causes open to get two arguments, both invalid. 这将导致open获得两个参数,两者均无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM