如果shell脚本中的条件无法运行

时间:2013-11-22 19:54:20

标签: linux shell

我正在尝试运行下面提到的脚本,但它给出了错误 - :

last=`grep 'xyz@gmail.com' test | sed 's/"//g'| awk  'BEGIN { FS = "," } ; {    print $8 }' | awk  'BEGIN { FS = " " } ; { print $1 }' | grep $(date +%Y-%m-%d --date='1 days ago') | head -1`
d=`(date +%Y-%m-%d --date='3 days ago')`
echo $d--$last
if [ $d == $last ]
 then 
 h=`grep 'xyz@gmail.com' test | wc -l`
 echo $h
 fi

文件测试的格式是 - :

"xyz@gmail.com","74","PR-460","Mob","one","i.3","2013-11-20 18:12:26","2013-11-21 11:55:33"
"xyz@gmail.com","74","PR-460","Mob","one","i.3","2013-11-20 18:12:26","2013-11-21 11:55:33"
"xyz@gmail.com","74","PR-460","Mob","one","i.3","2013-11-20 18:12:26","2013-11-21 11:55:33"

无错误: 第4行:[:2013-11-20:预期的整数表达式

2 个答案:

答案 0 :(得分:2)

使用[[ ]](不需要引号,可在bash,ksh和zsh中使用),或使用[ ]引用您的扩展名。也就是说,要么:

# if your script starts with #!/bin/bash
if [[ $d = $last ]]

# if your script starts with #!/bin/sh
if [ "$d" = "$last" ]

顺便说一下,grep | sed | awk非常讨厌 - awk可以在内部执行grep和sed所有操作。

答案 1 :(得分:0)

不是答案。看到grep / sed / awk / head的长管道让我感到很痛苦。单个awk调用可以替换它:

last=`grep 'xyz@gmail.com' test | sed 's/"//g'| awk  'BEGIN { FS = "," } ; {    print $8 }' | awk  'BEGIN { FS = " " } ; { print $1 }' | grep $(date +%Y-%m-%d --date='1 days ago') | head -1`

VS

last=$(
    awk -F, -v date=$(date -d yesterday +%F) '
        /xyz@gmail\.com/ {
            gsub(/"/,"")
            split($8, a, / /)
            if (a[1] ~ date) {
                print a[1]
                exit
            }
        }
    ' test
)