Reputation: 2160
How to echo the path of a file, found with a wildcard:
File path: /DIRECTORY_random_number/myFile
#!/bin/bash
FILE='DIRECTORY_'*'/myFile'
if [ -f $FILE ]; then
echo "this is the full path of this file..."
fi
Upvotes: 1
Views: 225
Reputation: 532218
You can press a for
loop to do this, especially in POSIX shells that don't have arrays.
for f in DIRECTORY_*/myFile; do
if [ -f "$f" ]; then
...
fi
break
done
Whether you need the break
statement is a judgement call. Your intention is that the pattern only matches a single file, but can you guarantee that? If you can, the break
isn't necessary. Of course, if it does match more than one file, how do you know that the first match is the one you actually want? Generally, it's a bad idea to make assumptions about your file system like this. Know which file it is you are looking for rather than assuming there is a unique match for your pattern.
Upvotes: 1
Reputation: 85865
Using a variable is not the best way to go about this. Also the globs are not expanded when used with single/double quote. Use an array and also if its a single file you are looking for, the full path can be retrieved using array expansion with *
shopt -s nullglob
filePath=(/DIRECTORY_*/newfile)
if (( "${#filePath[@]}" )); then
printf 'Matching file name found as %s\n' "${filePath[*]}"
fi
If you are using the bourne again shell, bash
, enable and extended shell option nullglob
, so that empty expansions are not part of the array.
This approach is far better than doing an unquoted variable expansion which would undergo Word-Splitting of your file names, if it contains special characters in the names.
Upvotes: 1