#!/bin/bash
# $n 脚本参数n
# $* 所有参数,将所有参数视为一个字符串
# $@ 所有参数,不含$0,将所有参数视为单个字符串
# $# 参数个数
# shift 参数左移,$#自动-1
# test expression 或者用 [expression] 代替 , 判断条件 [ = != -z(==0) -n(!=0) str(=="")(字符串判断) -eq -le -ge -lt -gt -ne(int判断)-a(and) -o[or] ! ]
# test file [-d dir -e 存在 -f file -r 进程可读文件 -s file长度不为0 -w 进程可写文件 -x 可执行文件 -L file为符号化链接]
# "" $有效
# '' $无效
# `` 命令有效
# 数值运算方法
# 1.sum=`expr $1 + $2` #要用空格隔开各个参数 \* /
# 2.sum=$(($1 + $2))
# 3.sum=$(expr $1 + $2)
# 字符串操作
# str=absdfadf , string必须是变量
# ${#str} 字符串长度
# expr match "$1" "$2" /expr $1 : $2 匹配子串开头的子串长度
# expr index $1 $2 子串索引
# ${string:position(n/0-n/ -n/n:len)} 提取子串
# ${string#substring} 截掉最短匹配的子串 ${string##substring} 最长匹配
# #换成%则表示从结尾开始
# ${string/substring/replcae} 替换匹配到的第一个字串
# ${string//substring/replcae} 所有
# ${string/%substring/replcae} 从结尾开始
# ${string/#substring/replcae} 如果子串是字串开头则替换
# basename / dirname 文件名/目录名截取
block_size=512 #B
env_bsize=32
bl2_bsize=600
bl1_bsize=16
x=$(($bl2_bsize * $block_size))
flag=0
if [ ! -f $1 ] #判断文件是否存在
then
echo "File not exist!"
else
file_name=`basename $1`
dir_name=`dirname $1` #获取dir不含最后一个/
echo "Generate sd_writer_file.bin.temp file"
cp $1 ${dir_name}/sd_writer_file.bin.temp
dd if=/dev/zero bs=1 count=1 seek=$x of=${dir_name}/sd_writer_file.bin.temp
echo "Generate sd_writer_file.dev.temp file"
sudo fdisk -l > ${dir_name}/sd_writer_file.dev.temp
if [ `dirname $2` != "/dev" ]
then
echo "SD not exist!"
else
# for i in `cat ${dir_name}/sd_writer_file.dev.temp`
# do
# echo $i
# if [ $i = $2: ]
# then
#
# break
# fi
# done
cat ${dir_name}/sd_writer_file.dev.temp | while read LINE
do
flag=0
for i in $LINE
do
if [ $flag -eq 0 -a $i = "Disk" ]
then
flag=$(( $flag + 1 ))
fi
if [ $flag -eq 1 -a $i = $2: ]
then
flag=$(( $flag + 1 ))
fi
if [ $flag -ge 2 ]
then
flag=$(( $flag + 1 ))
fi
if [ $flag -eq 6 ]
then
break
fi
done
if [ $flag -eq 6 ]
then
seek=$(( $i / $block_size - 1024 - 2 - $bl1_bsize ))
#echo "sudo dd if=${dir_name}/sd_writer_file.bin.temp of=$2 bs=$block_size count=$bl1_bsize seek=$seek"
sudo dd if=${dir_name}/sd_writer_file.bin.temp of=$2 bs=$block_size count=$bl1_bsize seek=$seek
seek=$(( $i / $block_size - 1024 - 2 - $bl1_bsize - $env_bsize - $bl2_bsize ))
#echo "sudo dd if=${dir_name}/sd_writer_file.bin.temp of=$2 bs=$block_size count=$bl2_bsize seek=$seek"
sudo dd if=${dir_name}/sd_writer_file.bin.temp of=$2 bs=$block_size count=$bl2_bsize seek=$seek
break
fi
done
fi
echo "remove all sd_writer_file.*.temp file"
rm -rf ${dir_name}/sd_writer_file.*.temp
fi