2012-07-26 75 views
3

我是新来的Stackoverflow,也是bash脚本的新手,所以请原谅我问这样一个问题。我在这里浏览了很多答案,但似乎没有任何效果。将grep&cut的结果放入一个变量中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 

它种作品作为输出是:

[email protected]:~/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 
[email protected]:~/bin$ 

所以我得到的卷曲度&的grep &切正确的文件名,但也有一些是错误的变量。当我在第5行打印它看起来好像没什么问题,但是当第12行打印出来时,看起来很有趣。另外,if语句不起作用,我确实在相同的目录中有该文件。

如果我输出curl的结果--head http://wordpress.org/latest.tar.gz | grep Content-Disposition |在文本文件中切割-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”在很多similiar问题建议在这里,但似乎什么也不做。有任何想法吗?

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 

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

+2

您的'new'变量以“\ r \ n”行结束 - HTTP发送结束。你需要删除它,但我不知道如何在'bash'中做到这一点。 – chepner 2012-07-26 15:52:58

+0

谢谢@chepner - 我只是将第4行改为:'new = $(curl --head http://wordpress.org/latest.tar.gz | grep Content-Disposition | cut -d'='-f 2 | tr -d'\ r \ n')',它就像一个魅力! – 2012-07-26 16:00:30

+0

+1格式良好的问题,明确的问题描述,样本输出,事先研究,补偿我希望我能做+4!欢迎并继续发布。 – shellter 2012-07-26 19:32:15

回答

1

以下是您的代码的工作版本,其中的更改评论了它们的制作原因。

#!/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 
+0

感谢您的答复,接受。似乎工作正常,学习awk和整体更好的编码实践是非常有用的。大! – 2012-07-27 19:53:17