您的位置:首页 > 运维架构 > Shell

shell 初始化二进制文件

2012-10-25 19:50 246 查看
项目中需要创建一个二进制文件,文件大小为512kb,文件的每一个字节初始化为0xff,没找到比较方便的工具,就l写了个shell脚本,顺便熟悉下shell编程。

#!/bin/bash

# author: lizhi <ddgooo@hotmail.com>

# date: 2012-09-25-11:33

# file: create-my-file.sh

# description: create binary file and init dada and size;

# eg. size:1KB name:test file created by command:

# ./create-my-file.sh test -byte ff 1024

# every byte value 0xFF

if [ $# -ne 4 ];then

echo "Use format: $0 filename datatype[-string -decimal -octal -hex -bit -byte] initdata initcount"

echo "datatype: define the \"initdata\" data \type,used:"

echo " -string fill file with any bytes string data "

echo " -decimal fill file with 4 bytes decimal number "

echo " -octal fill file with 4 bytes octal number"

echo " -hex fill file with 4 bytes byte data,eg. ffffffff "

echo " -bit fill file with 1 byte data,eg. 11101101 "

echo " -byte fill file with 1 byte data,eg. ff "

echo "initdata: set the init data,fill file with this dada"

echo "initcount: filled count"

exit 1

fi

filename=$1

datatype=$2

initdata=$3

initcount=$4

echo "filename=$filename datatype=$datatype initdata=$initdata initcount=$initcount"

# string data type

if [ "$datatype" == "-string" ]; then

datalen='expr length $initdata'

echo "data length $datalen"

counter=0

while [ "$counter" -lt "$initcount" ]

do

echo -n $initdata >> $filename

((counter++))

echo "counter=$counter initdata=$initdata"

done

exit 0

fi

# other data type

hexdata=$initdata

if [ "$datatype" == "-decimal" ]; then

hexdata=`echo "ibase=10; obase=16; $initdata" | bc`

elif [ "$datatype" == "-octal" ]; then

hexdata=`echo "ibase=8; obase=16; $initdata" | bc`

elif [ "$datatype" == "-bit" ]; then

hexdata=`echo "ibase=2; obase=16; $initdata" | bc`

elif [ "$datatype" != "-byte" ] && [ "$datatype" != "-hex" ]; then

echo "datatype error"

exit 1

fi

echo "hexdata=$hexdata"

# format data as FFFFFFFF

format_hexdata=`printf "%08x" 0x$hexdata`

echo "format_hexdata=$format_hexdata"

# sed parttern

if [ "$datatype" == "-bit" ] || [ "$datatype" == "-byte" ]; then

sed_partten="`echo $format_hexdata | sed 's/[0-9a-zA-Z]\{2\}/& /g' | awk '{print "\\\\x"$4}'`"

else

sed_partten="`echo $format_hexdata | sed 's/[0-9a-zA-Z]\{2\}/& /g' | awk '{print "\\\\x"$4 "\\\\x"$3 "\\\\x"$2 "\\\\x"$1}'`"

fi

echo "sed_partten=$sed_partten"

# write file,begin 0pos write 1byte

counter=0

while [ $counter -lt $initcount ]

do

echo -e -n "$sed_partten" >> $filename # -n: No Newline; -e: enable interpretation of backslash escapes

((counter++))

done

echo "successed"

exit 0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: