[shell] shell变量附值咨询,怪异

sh/bash/dash/ksh/zsh等Shell脚本
回复
kbens85
帖子: 16
注册时间: 2012-03-31 11:52

[shell] shell变量附值咨询,怪异

#1

帖子 kbens85 » 2012-03-31 11:54

今天做个测试,发现个问题,大家来看下,变量附值老有问题
例如:一个文件夹下面,有一个文件和一个md5值,两个需要比对一下md5是不是相同,如下:
#/bin/bash
set -x
remote_key1=$(head -1 aaa.md5)
key1=$(md5sum aaa.zip | awk '{print $1}' )
if [ $remote_key1 != `echo $key1` ];then
echo $key1
fi

++ head -1 aaa.md5
+ remote_key1=$'876b141d010fc7ca686a61b7139340f1\r'
++ md5sum aaa.zip
++ awk '{print $1}'
+ key1=6f2b1d6b2cf9938d4ba414e343633969
++ echo 6f2b1d6b2cf9938d4ba414e343633969
+ '[' $'876b141d010fc7ca686a61b7139340f1\r' '!=' 6f2b1d6b2cf9938d4ba414e343633969 ']'
+ echo 6f2b1d6b2cf9938d4ba414e343633969
6f2b1d6b2cf9938d4ba414e343633969

看里面这个remote_key1值,附值为$'876b141d010fc7ca686a61b7139340f1\r' 这个不正常啊,前面多个$,后面多个\r
在机器执行 head -1 aaa.md5 正常,求解啊
[root@puppet 2012]# head -1 aaa.md5
876b141d010fc7ca686a61b7139340f1
mad_frog
帖子: 55
注册时间: 2011-06-29 11:26

Re: [shell] shell变量附值咨询,怪异

#2

帖子 mad_frog » 2012-03-31 11:55

不懂@!~
头像
lilydjwg
论坛版主
帖子: 4258
注册时间: 2009-04-11 23:46
系统: Arch Linux
联系:

Re: [shell] shell变量附值咨询,怪异

#3

帖子 lilydjwg » 2012-03-31 13:57

正常。
1. $'xxx' 是 POSIX 标准里的字符串表示方法之一;
2. 你的那个文件使用 DOS 换行符,所以多了个 \r。
头像
drunkfish
帖子: 76
注册时间: 2011-04-30 17:17

Re: [shell] shell变量附值咨询,怪异

#4

帖子 drunkfish » 2012-03-31 15:49

同意楼上的观点
试试

代码: 全选

tr -d '\r' < dos_file > unix_file
改变下aaa.md5
怅怅莫怪少时年 百丈游丝易惹牵
何岁逢春不惆怅 何处逢情不可怜
杜曲梨花杯上雪 灞陵芳草梦中烟
前程两袖黄金泪 公案三生白骨禅
老后思量应不悔 衲衣持钵院门前
kbens85
帖子: 16
注册时间: 2012-03-31 11:52

Re: [shell] shell变量附值咨询,怪异

#5

帖子 kbens85 » 2012-03-31 18:08

正确,确实是这个问题,已修改过了,这样也行
remote_key1=$(sed -n -e "s/.$//;1p" aaa.md5)
:em09
aerofox
帖子: 1453
注册时间: 2008-05-24 8:30

Re: [shell] shell变量附值咨询,怪异

#6

帖子 aerofox » 2012-04-01 6:01

kbens85 写了:正确,确实是这个问题,已修改过了,这样也行
remote_key1=$(sed -n -e "s/.$//;1p" aaa.md5)
:em09
使用这条命令的风险就是,如果 aaa.md5 文件不是DOS格式的,则干坏事了。

其实检查 md5 是否正确,使用 md5sum 命令的 -c 参数最方便。
kbens85
帖子: 16
注册时间: 2012-03-31 11:52

Re: [shell] shell变量附值咨询,怪异

#7

帖子 kbens85 » 2012-04-05 10:18

aerofox 写了:
kbens85 写了:正确,确实是这个问题,已修改过了,这样也行
remote_key1=$(sed -n -e "s/.$//;1p" aaa.md5)
:em09
使用这条命令的风险就是,如果 aaa.md5 文件不是DOS格式的,则干坏事了。

其实检查 md5 是否正确,使用 md5sum 命令的 -c 参数最方便。

恩,谢谢,多谢指点
回复