如何缩短此bash脚本

时间:2013-06-26 18:53:02

标签: bash shell

我目前所拥有的是

cd /some/other/location
file_needed=$(ls -Altr `find -name "amey*1*" -print` | tail -1 | awk '{print $9}')
file_needed=${file_needed:2}
cp /some/other/location/${file_needed} .
yum -y install ${file_needed}

但我确信我有许多不必要的代码行,并且可以用更清晰的方式编写。

有什么建议吗?

3 个答案:

答案 0 :(得分:1)

你前两行绝对可以大大地重构成这样的东西:

find . -name "amey*1*" -exec stat -c "%Y %n" '{}' + | awk '{if ($1>cnt) {cnt=$1;f=$2}}
   END {print substr(f,3)}'

所以整个脚本可以变成:

file_needed=$(find /some/other/location -name "amey*1*" -exec stat -c "%Y %n" '{}' + | \
  awk '{if ($1>cnt) {cnt=$1;f=$2}} END {print substr(f,3)}')
cp /some/other/location/${file_needed} .
yum -y install ${file_needed}

答案 1 :(得分:1)

也许是这样的:

cp "$(ls -1tr /some/other/location/amey*1* | tail -1)" .

如果通配符匹配太多文件并导致失败,则此替代方法应该有效:

cp "$(ls -1tr /some/other/location | grep -E '^amey.*1' | tail -1)" .

答案 2 :(得分:0)

这个怎么样:

file_needed=$(find /some/other/location -maxdepth 1 -printf '%T@ %p\n' | sort -nr | head -1 | cut -c '23-')
cp "$file_needed" .
yum -y install "$file_needed"