tags:

views:

95

answers:

11

I use md5sum to generate a hash value for a file. But i only need to receive the hash value, not the file name.

md5=`md5sum ${my_iso_file}`
echo ${md5}

3abb17b66815bc7946cefe727737d295 ./iso/somefile.iso

How can i 'strip' the file name and only remain the value ?

+5  A: 

You can use cut to split the line on spaces and return only the first such field:

md5 = $(md5sum ${my_iso_file} | cut -d ' ' -f 1)
Brian Campbell
A: 
md5=`md5sum ${my_iso_file} | cut -b-32`
letronje
+2  A: 
md5="$(md5sum "${my_iso_file}")"
md5="${md5%% *}" # remove the first space and everything after it
echo "${md5}"
Gordon Davisson
Nice. One note -- on the first line you don't need quotes around `$()` (although they do no harm) but certainly need them around `${}`.
Roman Cheplyaka
@Roman: yeah, I tend to habitually quote any expansion (unless there's a reason not to) -- it's easier than keeping track of the cases where it's safe to skip the quotes. (Although in this case, I left them off the actual filename... stand by for an edit.)
Gordon Davisson
A: 

Another way:

md5=$(md5sum ${my_iso_file} | sed '/ .*//' )
codaddict
+2  A: 

Well another way :)

md5=`md5sum ${my_iso_file} | awk '{ print $1 }'`
jyzuz
A: 
md5=$(md5sum < index.html | head -c -4)
Dennis Williamson
A: 

One way:

set -- $(md5sum $file)
md5=$1

Another way:

md5=$(md5sum $file | while read sum file; do echo $sum; done)

Another way:

md5=$(set -- $(md5sum $file); echo $1)

(Do not try that with back-ticks unless you're very brave and very good with backslashes.)

The advantage of these solutions over other solutions is that they only invoke md5sum and the shell, rather than other programs such as awk or sed. Whether that actually matters is then a separate question; you'd probably be hard pressed to notice the difference.

Jonathan Leffler
A: 

Thx all, for the examples. As always, there are many ways to skin a cat :-))

Robertico
+1  A: 
md5sum $file | read SUM IGNORE

(read is a builtin, which will be faster than executing an external binary like awk or sed)

Tony
Nice. But what is there is already a variable named `IGNORE` :P
codaddict
A: 

On Mac OS X:

md5 -q file
trevor
A: 
md5=$(md5sum < $file | tr -d ' -')
pixelbeat