我需要将从/dev/uradom获得的5MB数据块写入分区中的特定位置.然后,我需要判断写入是否正确执行.我以前在C++中成功地做到了这一点,但现在我想在bash脚本中实现它.

我的C++代码包括:

  • 创建从/dev/uradom(RANDOM_ARRAY)填充的10MB数据数组
  • 使用open()打开分区
  • 使用lseek()导航到分区中所需的位置
  • 使用write()将数组写入分区
  • 关闭并重新打开分区,使用lseek导航回所需位置
  • 使用read()读取此位置的5MB,并用此数据填充另一个数组(WRITTEN_ARRAY)
  • 比较(RANDOM_ARRAY)和(WRITTEN_ARRAY)中的每个元素

我没有编写bash脚本的经验,但到目前为止,我已经做到了这一点,尽管它似乎不起作用:

random_data="$(cat /dev/urandom | head -c<5MB>)"

printf $random_data | dd of=<partition_path> bs=1 seek=<position_in_partition> count=<5MB>

file_data=$(dd if=<partition_path> bs=1 skip=<position_in_partition> count=<5MB>)

if [ "$random_data" == "$file_data" ]
then
 echo "data write successful"
fi

多亏了有帮助的 comments 者,我的脚本现在看起来像这样:

# get 10MB random data 
head -c<10MB> /dev/urandom > random.bin
# write 10MB random data to partition
dd if=random.bin of=<partition_location>
# copy the written data
dd if=<partition_location> count=<10MB/512 bytes> of=newdata.bin
# compare 
cmp random.bin newdata.bin

此时,cmp返回的第一个字符不同.查看cmp的详细输出,并得出newdata中的所有值.bin为0.

推荐答案

这里有一种更简单的方法,只需将数据保存在临时文件中.

#!/bin/sh

set -e

random_data=$(mktemp -t ideone.XXXXXXXX) || exit
trap 'rm -rf "$t"' EXIT

dd if=/dev/urandom bs=10240 count=512 of="$random_data"

dd if="$random_data" of=<partition_path> bs=1 seek=<position_in_partition> count=<5MB>

if dd if=<partition_path> bs=1 skip=<position_in_partition> count=<5MB> |
    cmp "$random_data"
then
 echo "data write successful"
fi

Linux相关问答推荐

Git - 打印以不同编码混合的文件

需要获取文件名、行号、模式在文件中的匹配位置

如何从 AWK 中的 CSV 列中获取中值? (Linux)

使用 bash 命令将文件从子文件夹复制到另一个

使用 sed 命令仅打印正则表达式匹配

从 curl 命令输出中获取值

每次来宾重新启动后 Vagrant 执行脚本或命令(vagrant up)

如何在 shell 脚本中只读取一个字符

关于 putenv() 和 setenv() 的问题

为什么这个命令会杀死我的 shell?

在 C 中检测 64 位编译

如何知道linux调度器时间片?

我可以告诉 Linux 不要换出特定进程的内存吗?

`cd //` 中的双斜杠 // 在 Linux 中是什么意思?

后缀 - status=bounced(未知用户myuser)

编译 OpenGL 程序 GL/glew.h 缺失

如何编写 Mono 守护程序

Linux(Ubuntu)终端-如何查看以前的页面不再可见

当我已经 ssh 进入远程机器时,如何 scp 回到本地?

Linux 上的 NuGet:获取响应流时出错