如何将带有空格的路径存储到bash中的变量中 [英] How to store a path with white spaces into a variable in bash

查看:148
本文介绍了如何将带有空格的路径存储到bash中的变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将/c/users/me/dir name存储到一个变量中,以将其传递给cd系统调用.

I want to store /c/users/me/dir name into a variable to pass it to cd system call.

键入时有效:

$ cd '/c/users/me/dir name'

$ cd /c/users/me/dir\ name

但如果我将其存储将不起作用:

but does not works if I store it:

$ dirname="'/c/users/me/dir name'"
$ cd $dirname
$ bash: cd: /c/users/me/dir: No such file or directory

与以下结果相同:

$ dirname=('/c/users/me/dir name')

$ dirname=(/c/users/me/dir\ name)

哪种是正确的存储方式?

Which is the right way to store it?

推荐答案

将路径变量用空格双引号,以保留它,

Double-quote your path variable with spaces, to preserve it,

dirName="/c/users/me/dir name"
cd "$dirName"

实际上,dirname是内置的shell,推荐,它使用备用名称以避免与实际命令混淆.

Actually, dirname is a shell built-in, recommend using an alternate name to avoid confusion with the actual command.

man bash页面上,

用双引号('')引起来的字符将保留引号中所有字符的文字值,但'$','`','\'除外,并且在启用历史记录扩展时,'! '.

Enclosing characters in double quotes (‘"’) preserves the literal value of all characters within the quotes, with the exception of ‘$’, ‘`’, ‘\’, and, when history expansion is enabled, ‘!’.

这篇关于如何将带有空格的路径存储到bash中的变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆