bashshellmd5sum

How to generate MD5 hash for the first n bytes in sh scripts?


I have the following php code line:

$md5_code = md5(file_get_contents($filePath, FALSE, NULL, 0, n_bytes));

that generates a MD5 hash code of a file's first n_bytes.

I would like to make a similar executable script/program, that gets the file and exports in a text file the MD5 hash code generated from the first n_bytes.

I think I need to mention that the script should work on both Windows and Linux machines.

The script can work something like this:

Is this even possible ?


Solution

  • Assuming you have functional Linux utilities on your window box, you can use bash and md5sum. You do not need to create a new file, as 'md5sum' can process data on stdin.

    # Modify variable to use parameters/values as needed.
    filename=...
    n_bytes=100
    out_file=md5.out
    head -c "$n_bytes" "$filename" | md5sum | awk '{ print $1 }'  > "$out_file"