运行此shell脚本时收到错误消息?第4行:[:缺少`]'

时间:2017-10-23 22:16:46

标签: bash

有人可以告诉我为什么我收到此错误消息吗?

#!/bin/bash
while read LINE; do
        curl -o /dev/null --silent --head --write-out '%{http_code}' "$LINE"
        if [ $http_code != 200]; then
                echo " $LINE URL not available"
                exit 1
        fi
        echo " $LINE"
        done < url-list.txt

1 个答案:

答案 0 :(得分:0)

您尝试使用$http_code,但从未声明它,而且在关闭测试]之前必须使用空格

所以:

#!/bin/bash
while read url; do
    http_code=$(curl -o /dev/null --silent --head --write-out '%{http_code}' "$url")
    if ((http_code != 200)); then
        echo " $url URL not available"
        exit 1
    fi
    echo " $url"
done < url-list.txt

注意:

  • (( ))适用于bash算术
  • 更喜欢[[ ]]形式的bash测试,它更强大,更不容易出错