bash 是否可以在 shell 中生成校验和(md5)字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37594759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to generate a checksum (md5 ) a string in a shell?
提问by user3914897
I would like to have a unique ID for filenames so I can iterate over the IDs and compare the checksums of the files? Is it possible to have a checksum for the name of the file so I can have a unique ID per filename? I would welcome other ideas.
我想要文件名的唯一 ID,以便我可以遍历 ID 并比较文件的校验和?是否可以对文件名进行校验和,以便每个文件名都有一个唯一的 ID?我欢迎其他想法。
回答by SerCe
Is it what you want?
是你想要的吗?
Plain string:
普通字符串:
serce@unit:~$ echo "Hello, checksum!" | md5sum
9f898618b071286a14d1937f9db13b8f -
And file content:
和文件内容:
serce@unit:~$ md5sum agent.yml
3ed53c48f073bd321339cd6a4c716c17 -
回答by Inian
Yes it is possible using md5sum
and basename $0
gives the name of current file
是的,可以使用md5sum
并basename $0
给出当前文件的名称
Assuming I have the script as below named md5Gen.sh
假设我有如下命名的脚本 md5Gen.sh
#!/bin/bash
mdf5string=$(basename "md5Gen.sh 911949bd2ab8467162e27c1b6b5633c0 -
" | md5sum )
echo -e `basename "$ printf '%s' "This-Filename" | md5sum
dd829ba5a7ba7bdf7a391f2e0bd7cd1f -
"` $mdf5string
Running the script would give me
运行脚本会给我
$ echo -n "This-Filename" | md5sum
dd829ba5a7ba7bdf7a391f2e0bd7cd1f -
回答by Inian
Yes, it is possible to obtain the MD5 of an string:
是的,可以获取字符串的 MD5:
$ echo "This-Filename" | md5sum
7ccba9dffa4baf9ca0e56c078aa09a07 -
It is important to understand that there is no newline at the end of the printed string. An equivalent in bash would be to use echo -n
:
重要的是要了解打印字符串的末尾没有换行符。bash 中的等效项是使用echo -n
:
$ echo -n "This-Filename" > infile
$ md5sum infile
dd829ba5a7ba7bdf7a391f2e0bd7cd1f infile
$ echo "This-Filename" > infile
$ md5sum infile
7ccba9dffa4baf9ca0e56c078aa09a07 infile
The -n
(valid in bash) is important because otherwise your hash would change with the inclusion of a newline that is not part of the text:
该-n
否则你的哈希将与包括换行符不是文本的一部分的改变(有效期在bash)是非常重要的:
That also apply to file contents:
这也适用于文件内容:
##代码##