Bash script to cd to directory with spaces in pathname

后端 未结 13 1754
旧时难觅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:19

    I found the solution below on this page:

    x="test\ me"  
    eval cd $x
    

    A combination of \ in a double-quoted text constant and an eval before cd makes it work like a charm!

    0 讨论(0)
  • 2020-11-28 21:20

    You can use any of:

    cd ~/"My Code"
    cd ~/M"y Code"
    cd ~/My" Code"
    

    You cannot use:

    cd ~"/My Code"
    

    The first works because the shell expands ~/ into $HOME/, and then tacks on My Code without the double quotes. The second fails because there isn't a user called '"' (double quote) for ~" to map to.

    0 讨论(0)
  • 2020-11-28 21:23

    use double quotes

    go () 
    { 
        cd "$*"
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-28 21:26

    After struggling with the same problem, I tried two different solutions that works:

    1. Use double quotes ("") with your variables.

    Easiest way just double quotes your variables as pointed in previous answer:

    cd "$yourPathWithBlankSpace"
    

    2. Make use of eval.

    According to this answer Unix command to escape spaces you can strip blank space then make use of eval, like this:

    yourPathEscaped=$(printf %q "$yourPathWithBlankSpace")
    eval cd $yourPathEscaped
    
    0 讨论(0)
  • 2020-11-28 21:29

    When you double-quote a path, you're stopping the tilde expansion. So there are a few ways to do this:

    cd ~/"My Code"
    cd ~/'My Code'
    

    The tilde is not quoted here, so tilde expansion will still be run.

    cd "$HOME/My Code"
    

    You can expand environment variables inside double-quoted strings; this is basically what the tilde expansion is doing

    cd ~/My\ Code
    

    You can also escape special characters (such as space) with a backslash.

    0 讨论(0)
提交回复
热议问题