Shell 中字符串转整数

Shell 中字符串转整数

我目前正在开发一个名为“dmCLI”的项目,这意味着“下载管理器命令行界面”。我正在使用curl 分部分下载文件。我的代码遇到了问题。我无法将字符串转换为整数。

这是我的完整代码。我还将我的代码上传到了 Github Repo。这里是: dmCLI GitHub 存储库

#!/bin/bash
RED='\033[0;31m'
NC='\033[0m'

help() {
    echo "dmcli [ FILENAME:path ] [ URL:uri ]"
}

echo -e "author: ${RED}@atahabaki${NC}"
echo -e "     __      _______   ____"
echo -e " ___/ /_ _  / ___/ /  /  _/"
echo -e "/ _  /  ' \/ /__/ /___/ /  "
echo -e "\_,_/_/_/_/\___/____/___/  "
echo -e "                           "
echo -e "${RED}Downloading${NC} has never been ${RED}easier${NC}.\n"

if [ $# == 2 ]
then
    filename=$1;
    url=$2
    headers=`curl -I ${url} > headers`
    contentlength=`cat headers | grep -E '[Cc]ontent-[Ll]ength:' | sed 's/[Cc]ontent-[Ll]ength:[ ]*//g'`
    acceptranges=`cat headers | grep -E '[Aa]ccept-[Rr]anges:' | sed 's/[Aa]ccept-[Rr]anges:[ ]*//g'`
    echo -e '\n'
    if [ "$acceptranges" = "bytes" ]
    then 
        echo File does not allow multi-part download.   
    else
        echo File allows multi-part download.
    fi
    echo "$(($contentlength + 9))"
    # if [acceptranges == 'bytes']
    # then
    # divisionresult = $((contentlength/9))
    # use for to create ranges...
else 
    help
fi

# First get Content-Length via regex or request,
# Then Create Sequences,
# After Start Downloading,
# Finally, re-assemble to 1 file.

我想将 contentlength 的值除以 9。我尝试了以下方法:

echo "$(($contentlength/9))"

它出现以下错误:

/9")语法错误:算术运算符无效(错误标记为“

我正在使用用 node.js 编写的 localhost。我添加了头部响应。它返回所请求文件的Content-Length,上面的dmCLI.sh正确获取了Content-Length值。

./dmcli.sh home.html http://127.0.0.1:404/

一个 HEAD 请求http://127.0.0.1:404/返回:内容长度:283,接受范围:字节

dmCLI 用于获取值,但是当我想访问它的值时,它不起作用。

简单的操作如下:

echo "$contentlength"

但我无法使用以下方法访问它:

echo "$contentlength bytes"

和这里:

echo "$(($contentlength + 9))"

返回 9 但我期待 292。问题出在哪里;为什么它不起作用?

答案1

下面的正则表达式将提取字节数,仅提取数字:

contentlength=$(
  LC_ALL=C sed '
    /^[Cc]ontent-[Ll]ength:[[:blank:]]*0*\([0-9]\{1,\}\).*$/!d
    s//\1/; q' headers
)

经过上述更改后,contentlength变量将仅由十进制数字组成(删除前导 0,因此 shell 不会将数字视为八进制),因此下面 2 行将显示相同的结果:

echo "$(($contentlength/9))"

echo "$((contentlength/9))"

答案2

headers=`curl -I ${url} > headers`
contentlength=`cat headers | grep -E '[Cc]ontent-[Ll]ength:' | sed 's/[Cc]ontent-[Ll]ength:[ ]*//g'`
echo "$(($contentlength/9))"

它出现以下错误:

/9")syntax error: invalid arithmetic operator (error token is "

HTTP 标头始终以 CR/LF 结尾,而不仅仅是 LF;你的`cat headers | ...`命令扩展将删除结尾的 LF,但保留 CR,这将导致奇怪的错误。

% var=`printf "%s\r\n" 333`
% echo var={$var}
}ar={333
% echo "$((var / 3))"
")syntax error: invalid arithmetic operator (error token is "

相关内容