我的问题是各种this question和this question的组合。我想在其路径中使用sudo权限挂载一个带空格的文件,如下所示:
sudo mount /path/to/mount/point /dir\\ with/spaces\\ in\\ name
如果路径中没有空格,我可以这样做,因为此用户对mount命令具有sudo权限:
Runtime.exec("sudo mount /path/to/mount/point /dir/without/spaces");
但是有空格,所以我试过了:
Runtime.exec("sudo mount /path/to/mount/point /dir\\ with/spaces\\ in\\ name");
这给了我"无法识别的arg' \'"或者来自mount的那种效果。使用单引号或双引号包围路径名也不起作用。
然后我尝试了:
Runtime.exec("sudo", "mount", "/path/to/mount/point", "/dir with/spaces in name");
当然失败了,因为sudo想要一些密码输入方法,即使我通常不需要为sudo mount输入密码。 Faaantastic。
对我来说,这似乎是一个问题。如果我使用单个String方法,我可以使sudo工作,或者如果我使用String数组方法,我可以获得路径名。我如何让两个工作?
答案 0 :(得分:1)
单个反斜杠不能逐字逐句写入字符串文字。应该转义反斜杠,因此请使用\\
:
Runtime.exec("sudo mount /path/to/mount/point /dir\\ with/spaces\\ in\\ name");
至于密码,如果您最近在同一个shell上输入密码,sudo
可能不会要求输入密码。如果您希望允许在没有超级用户权限的情况下安装给定路径(对于普通用户),请编辑其/etc/fstab
条目,如图所示here。
将user
添加到其选项中,例如:
/dev/sda8 /media/foo ext4 rw,user,exec 0 0
然后添加读写权限:
# chmod a+rw /media/foo
然后你的行可以是:
Runtime.exec("mount /path/to/mount/point /dir\\ with/spaces\\ in\\ name");
或
Runtime.exec("/bin/mount", "/path/to/mount/point", "/dir with/spaces in name");
或类似的。