4

我是 Stackoverflow 的新手,对 bash 脚本也很陌生,所以请原谅我提出这样一个愚蠢的问题。我真的在这里浏览了很多答案,但似乎没有什么对我有用。

我正在尝试制作这个小脚本来检查 wordpress.org 的最新版本,并检查我是否已经将该文件与脚本所在的目录放在同一目录中:

#!/bin/bash

function getVersion {
new=$(curl --head http://wordpress.org/latest.tar.gz | grep Content-Disposition | cut -d '=' -f 2)
echo "$new"
}

function checkIfAlreadyExists {
    if [ -e $new ]; then
        echo "File $new does already exist!"
    else
        echo "There is no file named $new in this folder!"
    fi
}

getVersion
checkIfAlreadyExists

它有点像输出:

jkw@xubuntu32-vb:~/bin$ ./wordpress_check 
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
wordpress-3.4.1.tar.gz
 in this folder! named wordpress-3.4.1.tar.gz
jkw@xubuntu32-vb:~/bin$ 

所以我用 curl&grep&cut 得到了正确的文件名,但是变量有问题。当我在第 5 行打印时,它看起来还不错,但是当我在第 12 行打印时,它看起来很有趣。此外,if 语句不起作用,我确实在同一目录中有文件。

如果我输出 curl --head http://wordpress.org/latest.tar.gz的结果| grep 内容处置 | cut -d '=' -f 2 在文本文件中,最后我似乎得到了一个新行,这可能是问题吗?如果我将命令通过管道传输到 xdd,它看起来像这样:

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
0000000: 776f 7264 7072 6573 732d 332e 342e 312e  wordpress-3.4.1.
0000010: 7461 722e 677a 0d0a                      tar.gz..

..我无法理解。

我试图通过tr '\n' '\0'tr -d '\n'按照这里很多类似问题中的建议通过管道传输命令,但它似乎什么也没做。有任何想法吗?

PS:我也想知道线条在哪里..

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0

..来我的shell输出。当我在终端中只运行命令curl --head http://wordpress.org/latest.tar.gz时,输出没有任何这样的行。

4

1 回答 1

2

这是您的代码的工作版本,其中注释了更改的原因。

#!/bin/bash

function latest_file_name {
    local url="http://wordpress.org/latest.tar.gz"

    curl -s --head $url | # Add -s to remove progress information
    # This is the proper place to remove the carridge return.
    # There is a program called dos2unix that can be used as well.
    tr -d '\r'          | #dos2unix
    # You can combine the grep and cut as follows
    awk -F '=' '/^Content-Disposition/ {print $2}'
}


function main {
    local file_name=$(latest_file_name)

    # [[ uses bash builtin test functionality and is faster.
    if [[ -e "$file_name" ]]; then
        echo "File $file_name does already exist!"
    else
        echo "There is no file named $file_name in this folder!"
    fi
}

main
于 2012-07-27T08:10:49.310 回答