开发者

Problem printing string in shell

I have a script written the unix shell lan开发者_JAVA百科guage (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!


You'll simplify your life by making effective use of single quotes as well as double quotes:

mountPoint="`df -h | grep $pth | tr -s ' ' | cut -d' ' -f6`"

The first step in debugging this is to remove the cut command and see what it produces:

mountPoint="`df -h | grep $pth | tr -s ' '`"
echo $mountPoint

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 the cut.

On my machine (a Mac), I get the output from df -h:

Filesystem      Size   Used  Avail Capacity  Mounted on
/dev/disk0s2   465Gi  189Gi  277Gi    41%    /
devfs          111Ki  111Ki    0Bi   100%    /dev
map -hosts       0Bi    0Bi    0Bi   100%    /net
map auto_home    0Bi    0Bi    0Bi   100%    /home
/dev/disk1s1   1.8Gi  8.8Mi  1.8Gi     1%    /Volumes/BLACKBERRY

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).


Move the \" before the -d in cut to after the -d.

mountPoint="`df -h | grep $pth | tr -s \" \"| cut -d \" \" -f6`"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜