Reputation: 24267
--Disclaimer--
I am open to better titles for this question.
I am trying to get the full name of a file matching: "target/cs-*.jar"
.
The glob is the version number.
Right now the version is 0.0.1-SNAPSHOT
.
So, below, I would like jar_location
to evaluate to cs-0.0.1-SNAPSHOT.jar
I've tried a few solutions, some of them work, some don't and I'm not sure what I'm missing.
Works
jar_location=( $( echo "target/cs-*.jar") )
echo "${jar_location[0]}"
Doesn't work
jar_location=$( echo "target/cs-*.jar")
echo "$jar_location"
jar_location=( "/target/cs-*.jar" )
echo "${jar_location}"
jar_location=$( ls "target/cs-*.jar" )
echo "${jar_location}"
--EDIT--
Added Filename Expansion to the title
Link to Bash Globbing / Filename Expansion
Similar question: The best way to expand glob pattern?
Upvotes: 0
Views: 1262
Reputation: 74596
If you're using bash, the best option is to use an array to expand the glob:
shopt -s nullglob
jar_locations=( target/cs-*.jar )
if [[ ${#jar_locations[@]} -gt 0 ]]; then
jar_location=${jar_locations##*/}
fi
Enabling nullglob
means that the array will be empty if there are no matches; without this shell option enabled, the array would contain the literal string target/cs-*.jar
in the case of no matches.
If the length of the array is greater than zero, then set the variable, using the expansion to remove everything up to the last /
from the first element of the array. This uses the fact that ${jar_locations[0]}
and $jar_locations
get you the same thing, namely the first element of the array. If you don't like that, you can always assign to a temporary variable.
An alternative for those with GNU find:
jar_location=$(find target -name 'cs-*.jar' -printf '%f' -quit)
This prints the filename of the first result and quits.
Note that if there is more than one file found, the output of these two commands may differ.
Upvotes: 3