Search code examples
linuxbashshellrhel

bash + how to set cli PATH with version in sub folder


Under /usr/hdp folder we can have only one the following sub-folders

2.6.5.0-292
2.6.4.0-91
2.6.0.3-8

example

ls /usr/hdp/
2.6.5.0-292  current  stack  file.txt

I want to use the following cli, and $VERSION could be one of the above versions

/usr/hdp/$VERSION/kafka/bin/kafka-reassign-partitions.sh

then I did the following in my bash script

[[ -d /usr/hdp/2.6.5.0-292 ]] && VERSION=2.6.5.0-292 
[[ -d /usr/hdp/2.6.4.0-91  ]] && VERSION=2.6.4.0-91  
[[ -d /usr/hdp/2.6.0.3-8   ]] && VERSION=2.6.0.3-8
/usr/hdp/$VERSION/kafka/bin/kafka-reassign-partitions.sh

Can we do the above setting in a more efficienct way without the test of [[ -d ...... ]]?


Solution

  • I don't think there is any way to make this more efficient and if your requirement is that the directory should exist, there is no way to avoid checking for that. But you can at least avoid repeating yourself by using a loop.

    for ver in 2.6.5.0-292 2.6.4.0-91 2.6.0.3-8; do
        if [[ -d "/usr/hdp/$ver" ]]; then
            VERSION=$ver
            break
        fi
    done
    

    The break causes the script to skip older versions as soon as it finds the newest in the list; your original code would weirdly do the opposite. If you genuinely want the oldest available version, reverse the ordering of the arguments to for.

    Not checking for any others once you find a match is an actual optimization here, albeit a very minor one.