我是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 Content Disposition|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' 附言:我也想知道线路在哪里。。 来看看我的shell输出。当我只运行命令时http://wordpress.org/latest.tar.gz % Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0
以下是您的代码的工作版本,其中注释了更改的原因。
#!/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