【发布时间】:2021-10-01 00:15:28
【问题描述】:
我正在尝试创建一个 shell 脚本,它会在计算后自动运行校验和命令并将当前和子目录中每个文件的校验和保存到一个文件中。如何通过变量或类似方法实现这一点?
我当前的脚本:
md5sum=1
sha1sum=2
sha256sum=3
sha512sum=4
# Ask user for checksum algorithm.
echo "Available checksum algorithms are MD5 [1], SHA-1 [2], SHA-256 [3], \
SHA-512 [4]."
echo "Checksum algorithm: "
read chkalg
# Create checksum file containing file checksums.
echo "Computing and saving list of checksums for all files recursively in \
directory."
if $chkalg == 1; then
find -type f -exec md5sum "{}" + > checksum-md5.txt
elif $chkalg == 2; then
find -type f -exec sha1sum "{}" + > checksum-sha1sum.txt
elif $chkalg == 3; then
find -type f -exec sha256sum "{}" + > checksum-sha256sum.txt
elif $chkalg == 4; then
find -type f -exec sha512sum "{}" + > checksum-sha512sum.txt
elif echo "Invalid choice."
fi
# Notify user of checksum file creation completion.
echo "Checksums saved to file."
【问题讨论】:
-
修改代码以从用户那里读取所需的文件名并在该文件上运行 find 命令。
-
shellcheck.net 会指出当前代码的一系列问题。
-
运行脚本时会发生什么?它会产生任何输出吗?是否写入了任何
*.txt文件?您在 stdout 或 stderr 上收到任何内容吗?如果*.txt文件被写入... 你期待的结果是对还是错? -
代码一直运行,直到调用变量。我收到的错误是
/directory/script.sh: 1: not found。我这里粘贴的时候已经替换了错误中的路径和文件名,但是是正确的。似乎变量存在问题。错误发生了 4 次。 -
@GordonDavisson 我使用了shellcheck.net 并解决了这个问题。谢谢你的链接。
标签: bash shell variables checksum