Bash script to cd to directory with spaces in pathname

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

提交回复
热议问题