Bash - change path to the folder with the highest version number

余生颓废 提交于 2019-12-11 17:27:19

问题


I have the below folder structure

MyPackage
  └── versions
      └── MyPackage-1.0
          └── src
          MyPackage-1.0.1
          └── src
          MyPackage-2.0
          └── src

I am writing a bash script to build the latest version of the package and retrieve the build artifact. Part of that step is to change to the directory of the latest package:

cd MyPackage/versions/MyPackage-2.0/src

How can I write my bash script such that it will always choose the highest version subfolder (so in this case MyPackage-2.0 but in the future it could become MyPackage-2.0.1 or MyPackage-2.1)?


回答1:


With the help of GNU sort you can do the following:

cd "$(printf "%s"$'\n' MyPackage/versions/* | sort -Vr | head -n1)"

Broken down:

$ printf "%s"$'\n' MyPackage/versions/*
MyPackage/versions/MyPackage-1.0
MyPackage/versions/MyPackage-1.0.1
MyPackage/versions/MyPackage-2.0
$ printf "%s"$'\n' MyPackage/versions/* | sort -Vr
MyPackage/versions/MyPackage-2.0
MyPackage/versions/MyPackage-1.0.1
MyPackage/versions/MyPackage-1.0
$ printf "%s"$'\n' MyPackage/versions/* | sort -Vr | head -n1
MyPackage/versions/MyPackage-2.0


来源:https://stackoverflow.com/questions/57805676/bash-change-path-to-the-folder-with-the-highest-version-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!