Bash script to cd to directory with spaces in pathname

后端 未结 13 1693
旧时难觅i
旧时难觅i 2020-11-28 21:14

I\'m using Bash on macOS X and I\'d like to create a simple executable script file that would change to another directory when it\'s run. However, the path to that director

13条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-28 21:24

    A single backslash works for me:

    ry4an@ry4an-mini:~$ mkdir "My Code"
    
    ry4an@ry4an-mini:~$ vi todir.sh
    
    ry4an@ry4an-mini:~$ . todir.sh 
    
    ry4an@ry4an-mini:My Code$ cat ../todir.sh 
    #!/bin/sh
    cd ~/My\ Code
    

    Are you sure the problem isn't that your shell script is changing directory in its subshell, but then you're back in the main shell (and original dir) when done? I avoided that by using . to run the script in the current shell, though most folks would just use an alias for this. The spaces could be a red herring.

提交回复
热议问题