简体   繁体   中英

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...... ]] ?

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.

If you can have only one of the folders 2.6.5.0-292 , 2.6.4.0-91 or 2.6.0.3-8 , then the assignment VERSION=2.6.* will expand to the unique and correct folder.

So your script could look like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM