【问题标题】:bash script if statement issuebash脚本if语句问题
【发布时间】:2019-08-15 12:39:10
【问题描述】:

我从另一个 bash 脚本调用以下脚本来检查文件更改。如果 SHA 从一次执行更改为下一次执行,则 google 文档已更新。

脚本(尝试)接受 google drive doc ID 作为参数,然后尝试几次以获取信息(因为 gdrive 随机失败)。结果有几行长,因此脚本对结果进行 SHA 以获得唯一的简短结果。

它正在工作(当 gdrive 将返回结果时),所以我添加了循环和失败消息以使其更加健壮,但是...

我必须对以下脚本中的 if 和可能的 while 语句做错了,因为即使 gdrive 信息结果失败,脚本也只会循环一次。此外,当要测试长度的字符串被故意设置为短时。

如果我有头发,我会把它拔掉。

#!/bin/bash
maxAttempts=10
minResult=100  # gdrive errors are about 80 characters

# If there was no parameter, give an error  
[[ -z $1 ]] && errorMsg="Error: no google docs ID provided as a parameter" && echo $errorMsg && exit 0

# With an ID, get the file info, which includes a timestamp and return the SHA
attemptCount=0
strLength=1 
while [[ "$strLength" < "$minResult" && "$attemptCount" < "$maxAttempts" ]];
do
    ((attemptCount++))
    fileInfo="$(gdrive info $1)"
    #fileInfo="TESTXXX" # use for testing different message lengths
    strLength=${#fileInfo}  # if under 100, the grive attempt failed
    timeStamp="$(echo -n $fileInfo | sha256sum )"
    echo $fileInfo
    if [[ $strLength < $minResult ]]; then
        sleep 10
        timeStamp="Failed to get timestamp after $attemptCount tries, or wrong ID provided"
    fi
done

#return the timestamp
echo $timeStamp

使用最后的 if 语句,我尝试了单方括号和双方括号、变量双引号、-gt 和

【问题讨论】:

  • comment。另外我建议您使用set -x 进行调试

标签: bash if-statement while-loop


【解决方案1】:

使用圆括号进行数值运算:

if (( strLength < minResult )); then

但请确保变量包含数值。这可以通过declare 来完成:

declare -i strLength
declare -i minResult

【讨论】:

  • 感谢您的快速响应。我也刚刚发现这些方法有效:while [[ "$var1" -lt "$var2 ]];if [[ "$var1" -lt "$var2 ]];then 我一定已经尝试了所有可能的组合,或者今天早些时候搞砸了 -lt -gt。
猜你喜欢
  • 2015-09-16
  • 2014-05-26
  • 1970-01-01
  • 2012-11-19
  • 1970-01-01
  • 2017-01-15
  • 2020-03-26
  • 1970-01-01
  • 2013-06-01
相关资源
最近更新 更多