在 shell 中打印字符串时出现问题
我有一个用 unix shell 语言编写的脚本(不是在 bash 或任何其他 shell 中,而是在 sh 中),它打印给定 USB 的挂载点(即,它采用 USB 的路径(例如 /dev/sdb1)作为争论)。 问题是
#!/bin/sh
# usage: get_mount [path]
# returns: mount pount of given usb path
pth=$1
echo $pth
mountPoint="`df -h | grep $pth | tr -s \" \"| cut \"-d \" -f6`"
echo $mountPoint
,当我运行这个时,它只打印一个空白字符串,我知道该命令有效,因为我在终端中尝试过它,没有问题:它只是将它分配给一个变量,这不起作用。有人有什么想法吗?提前谢谢!
I have a script written the unix shell language (NOT in bash or any other shell, in sh) that prints the mount point of a given usb (i.e, it takes the path of a usb (such as /dev/sdb1) as an argument). Here it is:
#!/bin/sh
# usage: get_mount [path]
# returns: mount pount of given usb path
pth=$1
echo $pth
mountPoint="`df -h | grep $pth | tr -s \" \"| cut \"-d \" -f6`"
echo $mountPoint
The problem is, when I run this, it just prints a blank string, and I know the command works because I've tried it in a terminal with no problem: it's just assigning it to a variable is what's not working. Anyone have any ideas? Thx in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通过有效地使用单引号和双引号,您将简化您的生活:
调试此命令的第一步是删除
cut
命令并查看它生成的内容:它是否仍然打印 6 (或更多)列?
请注意,如果命令的参数拼写错误,则 grep 不会将任何内容传递给 cut。
在我的机器(Mac)上,我从 df -h 获得输出:
请注意,某些文件系统名称中包含空格。它不太可能成为您问题的一个因素,但它可能会导致问题发生(挂载点是字段 7)。
You'll simplify your life by making effective use of single quotes as well as double quotes:
The first step in debugging this is to remove the
cut
command and see what it produces:Does it still print 6 (or more) columns?
Note that if you misspell the argument to the command, then the
grep
will pass nothing through to thecut
.On my machine (a Mac), I get the output from
df -h
:Note that some of the file system names have spaces in them. It is unlikely to be a factor in your problem, but it could throw things off (the mount point is then field 7).
将 cut 中 -d 之前的 \" 移动到 -d 之后。
Move the \" before the -d in cut to after the -d.