Check if a file exists with wildcard in shell script [duplicate]
This question already has an answer here:
Test whether a glob has any matches in bash
18 answers
I'm trying to check if a file exists, but with a wildcard. Here is my example:
if [ -f "xorg-x11-fonts*" ]; then
printf "BLAH"
fi
I have also tried it without the double quotes.
shell sh wildcard
marked as duplicate by John Kugelman
StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
May 31 '18 at 8:31
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
add a comment |
This question already has an answer here:
Test whether a glob has any matches in bash
18 answers
I'm trying to check if a file exists, but with a wildcard. Here is my example:
if [ -f "xorg-x11-fonts*" ]; then
printf "BLAH"
fi
I have also tried it without the double quotes.
shell sh wildcard
marked as duplicate by John Kugelman
StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
May 31 '18 at 8:31
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
17
Two bugs with your code: (1) The asterisk has to be outside the double quotes (a quoted asterisk loses it special wildcard meaning), and (2) if multiple files match the pattern, multiple arguments will be passed to the[
command, most likely causing[
to exit with an error and therefore be interpreted as no files matching.
– Richard Hansen
Jun 17 '11 at 6:31
add a comment |
This question already has an answer here:
Test whether a glob has any matches in bash
18 answers
I'm trying to check if a file exists, but with a wildcard. Here is my example:
if [ -f "xorg-x11-fonts*" ]; then
printf "BLAH"
fi
I have also tried it without the double quotes.
shell sh wildcard
This question already has an answer here:
Test whether a glob has any matches in bash
18 answers
I'm trying to check if a file exists, but with a wildcard. Here is my example:
if [ -f "xorg-x11-fonts*" ]; then
printf "BLAH"
fi
I have also tried it without the double quotes.
This question already has an answer here:
Test whether a glob has any matches in bash
18 answers
shell sh wildcard
shell sh wildcard
edited Oct 11 '16 at 4:58
tripleee
94.9k13133188
94.9k13133188
asked Jun 15 '11 at 19:50
DannyDanny
1,92251826
1,92251826
marked as duplicate by John Kugelman
StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
May 31 '18 at 8:31
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
marked as duplicate by John Kugelman
StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
May 31 '18 at 8:31
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
17
Two bugs with your code: (1) The asterisk has to be outside the double quotes (a quoted asterisk loses it special wildcard meaning), and (2) if multiple files match the pattern, multiple arguments will be passed to the[
command, most likely causing[
to exit with an error and therefore be interpreted as no files matching.
– Richard Hansen
Jun 17 '11 at 6:31
add a comment |
17
Two bugs with your code: (1) The asterisk has to be outside the double quotes (a quoted asterisk loses it special wildcard meaning), and (2) if multiple files match the pattern, multiple arguments will be passed to the[
command, most likely causing[
to exit with an error and therefore be interpreted as no files matching.
– Richard Hansen
Jun 17 '11 at 6:31
17
17
Two bugs with your code: (1) The asterisk has to be outside the double quotes (a quoted asterisk loses it special wildcard meaning), and (2) if multiple files match the pattern, multiple arguments will be passed to the
[
command, most likely causing [
to exit with an error and therefore be interpreted as no files matching.– Richard Hansen
Jun 17 '11 at 6:31
Two bugs with your code: (1) The asterisk has to be outside the double quotes (a quoted asterisk loses it special wildcard meaning), and (2) if multiple files match the pattern, multiple arguments will be passed to the
[
command, most likely causing [
to exit with an error and therefore be interpreted as no files matching.– Richard Hansen
Jun 17 '11 at 6:31
add a comment |
21 Answers
21
active
oldest
votes
The simplest should be to rely on ls
return value (it returns non-zero when the files do not exist):
if ls /path/to/your/files* 1> /dev/null 2>&1; then
echo "files do exist"
else
echo "files do not exist"
fi
I redirected the ls
output to make it completely silent.
EDIT: Since this answer has got a bit of attention (and very useful critic remarks as comments), here is an optimization that also relies on glob expansion, but avoids the use of ls
:
for f in /path/to/your/files*; do
## Check if the glob gets expanded to existing files.
## If not, f here will be exactly the pattern above
## and the exists test will evaluate to false.
[ -e "$f" ] && echo "files do exist" || echo "files do not exist"
## This is all we needed to know, so we can break after the first iteration
break
done
This is very similar to @grok12's answer, but it avoids the unnecessary iteration through the whole list.
7
A word of warning: In the Debian Almquist Shell (dash
) — installed at/bin/sh
in Debian and Ubuntu —&>
seems to discard the exit code and that breaks this solution. A workaround is to redirect with> /dev/null 2>&1
instead.
– qerub
Nov 20 '11 at 18:42
18
ls
can be quite slow on a directory with many files (probably due to sorting). You may want to turn off sorting with-U
, at least.
– musiphil
Jun 21 '12 at 21:01
Would it be better to list the files into text file and look at that if you were dealing with a lot of searches?
– Mike Q
Jun 13 '14 at 16:35
1
@CostiCiudatu have you checked how that alternative works when there are spaces in the directory name? Wouldn't e.g.for f in /path/to/your files*
interpreted as two arguments,/path/to/your
andfiles*
? I've tried putting double-quotes around, but that didn't work out (never finds a file, even if there's one).
– Izzy
Dec 13 '14 at 21:00
3
@Izzy, you are supposed to put that in double quotes, but leave the*
outside:for f in "/path/to/your files"*
should work.
– Costi Ciudatu
Dec 13 '14 at 23:02
|
show 6 more comments
If your shell has a nullglob option and it's turned on, a wildcard pattern that matches no files will be removed from the command line altogether. This will make ls see no pathname arguments, list the contents of the current directory and succeed, which is wrong. GNU stat, which always fails if given no arguments or an argument naming a nonexistent file, would be more robust. Also, the &> redirection operator is a bashism.
if stat --printf='' /path/to/your/files* 2>/dev/null
then
echo found
else
echo not found
fi
Better still is GNU find, which can handle a wildcard search internally and exit as soon as at it finds one matching file, rather than waste time processing a potentially huge list of them expanded by the shell; this also avoids the risk that the shell might overflow its command line buffer.
if test -n "$(find /dir/to/search -maxdepth 1 -name 'files*' -print -quit)"
then
echo found
else
echo not found
fi
Non-GNU versions of find might not have the -maxdepth option used here to make find search only the /dir/to/search instead of the entire directory tree rooted there.
6
Lettingfind
handle the wildcard is best becausebash
, as it expands the pattern, tries to sort the list of the matching file names, which is wasteful and can be expensive.
– musiphil
Jun 21 '12 at 21:10
@musiphil Launching an external process such asfind
is even more wasteful if there are only a few files (or none) in the directory.
– dolmen
Feb 24 '17 at 16:46
@dolmen: You are right. I guess it all depends on the situation; on the other hand, if there are a huge number of files, the wildcard expansion ofbash
can take more time than launchingfind
.
– musiphil
Mar 13 '17 at 18:48
@musiphil Even worse: if there is a huge number of the wildcard expansion can simply fail. But in that case, expanding the huge output offind
will probably fail too. Note also that listing all files with find just to then test if that output is empty or not is a big waste of resources.
– dolmen
Apr 13 '17 at 7:41
1
@dolmen: Runningfind
with-quit
as described in @flabdablet's post will not suffer from a huge number of files, because it quits as soon as it finds the first match and thus will not list all files. So it is not as big a waste of resources as you suggest. Moreover,find
doesn't simply "expand" the wildcard as the shell does, but checks each file it finds against the pattern to see if it is a match, so it doesn't fail for a huge number of files.
– musiphil
Apr 25 '17 at 1:34
|
show 1 more comment
Here is my answer -
files=(xorg-x11-fonts*)
if [ -e "${files[0]}" ];
then
printf "BLAH"
fi
You should addunsetopt nomatch
if zsh reports errors.
– Chih-Hsuan Yen
Jan 3 '15 at 9:38
5
andshopt -s nullglob
forbash
– nhed
Jun 27 '16 at 23:28
It shouild perhaps be pointed out more clearly that using an array makes this decidedly non-POSIXsh
.
– tripleee
Sep 26 '17 at 9:11
add a comment |
for i in xorg-x11-fonts*; do
if [ -f "$i" ]; then printf "BLAH"; fi
done
This will work with multiple files and with white space in file names.
4
It will print multiple "BLAH" if there are multiple matches. Maybe add abreak
to exit the loop after the first match.
– tripleee
May 27 '16 at 18:19
1
This (with @tripleee ‘s break) gets my vote. By using only native globbing and the file test operator, it avoids even raising the question of corner cases, that comes with using commands like ls or find or from forwarding globs. I think it is free of all the issues, like names with blanks, nullglob setting and bashisms, that were raised for some other answers. I made a function of it:existsAnyFile () { for file; do [ -f "$file" ] && return 0; done; false; }
– sdenham
Jun 30 '16 at 15:49
Note this gets a stat failure if xorg-x11-fonts* does not exist, which is probably not what you want.
– rfay
Nov 8 '18 at 23:04
add a comment |
You can do the following:
set -- xorg-x11-fonts*
if [ -f "$1" ]; then
printf "BLAH"
fi
This works with sh and derivates: ksh and bash. It doesn't create any sub-shell. $(..)and `...` commands create a sub-shell : they fork a process, and they are inefficient. Of course it works with several files, and this solution can be the fastest, or second to the fastest one.
It works too when there's no matches. There isn't need to use nullglob as one of the comentatators say. $1 will contain the origintal test name, therefore the test -f $1 won't success, because the $1 file doesn't exist.
The most portable solution!
– dolmen
Feb 24 '17 at 17:03
1
Alas, it doesn't work when there's no matches. $1 will contain the original test name, including the *. You could set "nullglob" in bash so it WILL blank out. THat's not portable, though :)
– Chris Cogdon
Mar 9 '18 at 20:55
Chris, when there isn't a match, $1 will contain the origintal test name, including the * as you say. Then the test: [ -f "$1" ] won't be sucessfull because the file "*" doesn't exist. Therefore you don't need nullglob, or other tricks. It is 100% portable.
– joseyluis
May 16 '18 at 9:59
add a comment |
UPDATE:
Okay, now I definitely have the solution:
files=$(ls xorg-x11-fonts* 2> /dev/null | wc -l)
if [ "$files" != "0" ]
then
echo "Exists"
else
echo "None found."
fi
> Exists
In my shell (zsh) it works if there is only one match to the glob, otherwise it expands all the files and the test fails (too many arguments.)
– Edward Thomson
Jun 15 '11 at 20:02
Update my code. I'm sure this works, I just installed zsh and tested.
– Swift
Jun 15 '11 at 20:20
Reupdated. My bad.
– Swift
Jun 15 '11 at 20:33
1
ls
can be quite slow on a directory with many files (probably due to sorting). You may want to turn off sorting with-U
, at least.
– musiphil
Jun 21 '12 at 21:01
If the globbing matches a directory name, ls will spit out the contentes of that directory which may cause false positives.
– William Everett
Mar 21 '16 at 22:00
|
show 1 more comment
Maybe this will help someone:
if [ "`echo xorg-x11-fonts*`" != "xorg-x11-fonts*" ]; then
printf "BLAH"
fi
1
This is the simplest, easiest and most elegant answer that actually works!
– Serge Stroobandt
Jun 28 '15 at 14:00
2
@SergeStroobandt Not sure I agree. The command substitution may be necessary here, but it tickles my cringe reflex.
– tripleee
May 27 '16 at 18:21
2
yea... like what if the file with the literal namexorg-x11-fonts*
exists?
– mlathe
Oct 12 '16 at 18:32
2
Not elegant at all because it forks a sub shell to run the echo command.
– dolmen
Feb 24 '17 at 16:52
1
not elegant, ugly AF
– nhed
Sep 11 '17 at 15:18
add a comment |
The question wasn't specific to Linux/Bash so I thought I would add the Powershell way - which treats wildcards different - you put it in the quotes like so below:
If (Test-Path "./output/test-pdf-docx/Text-Book-Part-I*"){
Remove-Item -force -v -path ./output/test-pdf-docx/*.pdf
Remove-Item -force -v -path ./output/test-pdf-docx/*.docx
}
I think this is helpful because the concept of the original question covers "shells" in general not just Bash or Linux, and would apply to Powershell users with the same question too.
add a comment |
Strictly speaking, if you only want to print "Blah" here is the solution :
find . -maxdepth 1 -name 'xorg-x11-fonts*' -printf 'BLAH' -quit
Here is another way :
doesFirstFileExist(){
test -e "$1"
}
if doesFirstFileExist xorg-x11-fonts*
then printf "BLAH"
fi
But I think the most optimal is as follow, because it won't try to sort file names :
if [ -z `find . -maxdepth 1 -name 'xorg-x11-fonts*' -printf 1 -quit` ]
then printf "BLAH"
fi
You can also use-exec
option of find like this:find . -maxdepth 1 -name '*.o' -exec rm {} ;
– user3405291
Mar 14 '18 at 7:49
add a comment |
The bash code I use
if ls /syslog/*.log > /dev/null 2>&1; then
echo "Log files are present in /syslog/;
fi
Thanks!
add a comment |
Here's a solution for your specific problem that doesn't require for
loops or external commands like ls
, find
and the like.
if [ "$(echo xorg-x11-fonts*)" != "xorg-x11-fonts*" ]; then
printf "BLAH"
fi
As you can see, it's just a tad more complicated than what you were hoping for, and relies on the fact that if the shell is not able to expand the glob, it means no files with that glob exist and echo
will output the glob as is, which allows us to do a mere string comparison to check whether any of those files exist at all.
If we were to generalize the procedure, though, we should take into account the fact that files might contain spaces within their names and/or paths and that the glob char could rightfully expand to nothing (in your example, that would be the case of a file whose name is exactly xorg-x11-fonts).
This could be achieved by the following function, in bash.
function doesAnyFileExist {
local arg="$*"
local files=($arg)
[ ${#files[@]} -gt 1 ] || [ ${#files[@]} -eq 1 ] && [ -e "${files[0]}" ]
}
Going back to your example, it could be invoked like this.
if doesAnyFileExist "xorg-x11-fonts*"; then
printf "BLAH"
fi
Glob expansion should happen within the function itself for it to work properly, that's why I put the argument in quotes and that's what the first line in the function body is there for: so that any multiple arguments (which could be the result of a glob expansion outside the function, as well as a spurious parameter) would be coalesced into one. Another approach could be to raise an error if there's more than one argument, yet another could be to ignore all but the 1st argument.
The second line in the function body sets the files
var to an array constituted by all the file names that the glob expanded to, one for each array element. It's fine if the file names contain spaces, each array element will contain the names as is, including the spaces.
The third line in the function body does two things:
It first checks whether there's more than one element in the array. If so, it means the glob surely got expanded to something (due to what we did on the 1st line), which in turn implies that at least one file matching the glob exist, which is all we wanted to know.
If at step 1. we discovered that we got less than 2 elements in the array, then we check whether we got one and if so we check whether that one exist, the usual way. We need to do this extra check in order to account for function arguments without glob chars, in which case the array contains only one, unexpanded, element.
1
This is inefficient because$(..)
launches a sub-shell.
– dolmen
Feb 24 '17 at 16:59
@dolmen a sub-shell is just a process like any other. The accepted answer launches thels
command, which for all intent and purposes is as efficient (or inefficient) as a sub-shell is.
– Fabio A.
Mar 28 '17 at 9:31
I've never written that the accepted answer is better and that I would have accepted if I had been the submitter.
– dolmen
Apr 13 '17 at 7:34
Notice that the generalized method I explain in this very same answer doesn't use any subshell at all.
– Fabio A.
Apr 13 '17 at 11:21
add a comment |
I use this:
filescount=`ls xorg-x11-fonts* | awk 'END { print NR }'`
if [ $filescount -gt 0 ]; then
blah
fi
2
wc -l
is more efficient thanawk
for this task.
– dolmen
Feb 24 '17 at 16:57
1
Counting the number of results is an antipattern anyway. Usually you simply want to see whetherls
returned success or not (or better yet avoidls
too and use the shell's built-in functionality).
– tripleee
Sep 26 '17 at 9:10
add a comment |
IMHO it's better to use find
always when testing for files, globs or directories. The stumbling block in doing so is find
's exit status: 0 if all paths were traversed successfully, >0 otherwise. The expression you passed to find
creates no echo in its exit code.
The following example tests if a directory has entries:
$ mkdir A
$ touch A/b
$ find A -maxdepth 0 -not -empty -print | head -n1 | grep -q . && echo 'not empty'
not empty
When A
has no files grep
fails:
$ rm A/b
$ find A -maxdepth 0 -not -empty -print | head -n1 | grep -q . || echo 'empty'
empty
When A
does not exist grep
fails again because find
only prints to stderr:
$ rmdir A
$ find A -maxdepth 0 -not -empty -print | head -n1 | grep -q . && echo 'not empty' || echo 'empty'
find: 'A': No such file or directory
empty
Replace -not -empty
by any other find
expression, but be careful if you -exec
a command that prints to stdout. You may want to grep for a more specific expression in such cases.
This approach works nicely in shell scripts. The originally question was to look for the glob xorg-x11-fonts*
:
if find -maxdepth 0 -name 'xorg-x11-fonts*' -print | head -n1 | grep -q .
then
: the glob matched
else
: ...not
fi
Note that the else-branched is reached if xorg-x11-fonts*
had not matched, or find
encountered an error. To distinguish the case use $?
.
1
You probably meant -maxdepth 1 when using -name, since -maxdepth 0 will look at the current directory and not its contents.
– Chris Cogdon
Jul 29 '16 at 23:40
add a comment |
if [ `ls path1/* path2/* 2> /dev/null | wc -l` -ne 0 ]; then echo ok; else echo no; fi
add a comment |
Try this
fileTarget="xorg-x11-fonts*"
filesFound=$(ls $fileTarget) # 2014-04-03 edit 2: removed dbl-qts around $(...)
edit 2014-04-03 (removed dbl-quotes and added test file 'Charlie 22.html' (2 spaces)
case ${filesFound} in
"" ) printf "NO files found for target=${fileTarget}n" ;;
* ) printf "FileTarget Files found=${filesFound}n" ;;
esac
Test
fileTarget="*.html" # where I have some html docs in the current dir
FileTarget Files found=Baby21.html
baby22.html
charlie 22.html
charlie21.html
charlie22.html
charlie23.html
fileTarget="xorg-x11-fonts*"
NO files found for target=xorg-x11-fonts*
Note that this only works in the current directory, or where the var fileTarget
includes the path you are want to inspect.
Your code will fail iffileTarget
contains whitespace (e.g.,fileTarget="my file*"
).
– Richard Hansen
Jun 17 '11 at 6:34
@RichardHansen what the solution when there is whitespace?
– Ross
Mar 28 '14 at 22:57
@Ross: Use the accepted answer:if ls "my file"* >/dev/null 2>&1; then ...
– Richard Hansen
Mar 29 '14 at 2:59
@RichardHansen thanks, sorry – not working for me. Have it fixed now .
– Ross
Apr 2 '14 at 9:44
1
@Ross, I've added an edit to mine that should work with files with spaces. Basicallycase "${filesFound}" in ....
. Good luck to all.
– shellter
Apr 2 '14 at 11:23
|
show 2 more comments
How about
if ls -l | grep -q 'xorg-x11-fonts.*' # grep needs a regex, not a shell glob
then
# do something
else
# do something else
fi
1
No, don't usels
in scripts and the.*
wildcard is redundant (you probably meantgrep -q '^xorg-x1-fonts'
).
– tripleee
Sep 26 '17 at 9:08
why not parsels
– phuclv
May 31 '18 at 8:48
add a comment |
If there is a huge amount of files on a network folder using the wildcard is questionable (speed, or command line arguments overflow).
I ended up with:
if [ -n "$(find somedir/that_may_not_exist_yet -maxdepth 1 -name *.ext -print -quit)" ] ; then
echo Such file exists
fi
add a comment |
You can also cut other files out
if [ -e $( echo $1 | cut -d" " -f1 ) ] ; then
...
fi
this would be slow because of the subshell. And what if the file name contains space?
– phuclv
May 31 '18 at 8:49
add a comment |
Using new fancy shmancy features in ksh, bash, and zsh shells (this example doesn't handle spaces in filenames):
# Declare a regular array (-A will declare an associative array. Kewl!)
declare -a myarray=( /mydir/tmp*.txt )
array_length=${#myarray[@]}
# Not found if the 1st element of the array is the unexpanded string
# (ie, if it contains a "*")
if [[ ${myarray[0]} =~ [*] ]] ; then
echo "No files not found"
elif [ $array_length -eq 1 ] ; then
echo "File was found"
else
echo "Files were found"
fi
for myfile in ${myarray[@]}
do
echo "$myfile"
done
Yes, this does smell like Perl. Glad I didn't step in it ;)
add a comment |
Found a couple of neat solutions worth sharing. The first still suffers from "this will break if there's too many matches" problem:
pat="yourpattern*" matches=($pat) ; [[ "$matches" != "$pat" ]] && echo "found"
(Recall that if you use an array without the [ ]
syntax, you get the first element of the array.)
If you have "shopt -s nullglob" in your script, you could simply do:
matches=(yourpattern*) ; [[ "$matches" ]] && echo "found"
Now, if it's possible to have a ton of files in a directory, you're pretty well much stuck with using find:
find /path/to/dir -maxdepth 1 -type f -name 'yourpattern*' | grep -q '.' && echo 'found'
add a comment |
man test
if [ -e file ]; then
...
fi
will work for dirfile.
regards
9
This will not work with wildcards (which is what is asked in this question). If it matches more than one file you will getbash: [: too many arguments
– user000001
Apr 17 '13 at 13:28
1
A little unfair as this works very well on Solaris........
– SnazzyBootMan
Oct 9 '15 at 14:47
heh, old post, thanks for the support Chris - i was indeed working with Solaris back then as well.
– Shokodemon
Sep 24 '17 at 13:09
add a comment |
21 Answers
21
active
oldest
votes
21 Answers
21
active
oldest
votes
active
oldest
votes
active
oldest
votes
The simplest should be to rely on ls
return value (it returns non-zero when the files do not exist):
if ls /path/to/your/files* 1> /dev/null 2>&1; then
echo "files do exist"
else
echo "files do not exist"
fi
I redirected the ls
output to make it completely silent.
EDIT: Since this answer has got a bit of attention (and very useful critic remarks as comments), here is an optimization that also relies on glob expansion, but avoids the use of ls
:
for f in /path/to/your/files*; do
## Check if the glob gets expanded to existing files.
## If not, f here will be exactly the pattern above
## and the exists test will evaluate to false.
[ -e "$f" ] && echo "files do exist" || echo "files do not exist"
## This is all we needed to know, so we can break after the first iteration
break
done
This is very similar to @grok12's answer, but it avoids the unnecessary iteration through the whole list.
7
A word of warning: In the Debian Almquist Shell (dash
) — installed at/bin/sh
in Debian and Ubuntu —&>
seems to discard the exit code and that breaks this solution. A workaround is to redirect with> /dev/null 2>&1
instead.
– qerub
Nov 20 '11 at 18:42
18
ls
can be quite slow on a directory with many files (probably due to sorting). You may want to turn off sorting with-U
, at least.
– musiphil
Jun 21 '12 at 21:01
Would it be better to list the files into text file and look at that if you were dealing with a lot of searches?
– Mike Q
Jun 13 '14 at 16:35
1
@CostiCiudatu have you checked how that alternative works when there are spaces in the directory name? Wouldn't e.g.for f in /path/to/your files*
interpreted as two arguments,/path/to/your
andfiles*
? I've tried putting double-quotes around, but that didn't work out (never finds a file, even if there's one).
– Izzy
Dec 13 '14 at 21:00
3
@Izzy, you are supposed to put that in double quotes, but leave the*
outside:for f in "/path/to/your files"*
should work.
– Costi Ciudatu
Dec 13 '14 at 23:02
|
show 6 more comments
The simplest should be to rely on ls
return value (it returns non-zero when the files do not exist):
if ls /path/to/your/files* 1> /dev/null 2>&1; then
echo "files do exist"
else
echo "files do not exist"
fi
I redirected the ls
output to make it completely silent.
EDIT: Since this answer has got a bit of attention (and very useful critic remarks as comments), here is an optimization that also relies on glob expansion, but avoids the use of ls
:
for f in /path/to/your/files*; do
## Check if the glob gets expanded to existing files.
## If not, f here will be exactly the pattern above
## and the exists test will evaluate to false.
[ -e "$f" ] && echo "files do exist" || echo "files do not exist"
## This is all we needed to know, so we can break after the first iteration
break
done
This is very similar to @grok12's answer, but it avoids the unnecessary iteration through the whole list.
7
A word of warning: In the Debian Almquist Shell (dash
) — installed at/bin/sh
in Debian and Ubuntu —&>
seems to discard the exit code and that breaks this solution. A workaround is to redirect with> /dev/null 2>&1
instead.
– qerub
Nov 20 '11 at 18:42
18
ls
can be quite slow on a directory with many files (probably due to sorting). You may want to turn off sorting with-U
, at least.
– musiphil
Jun 21 '12 at 21:01
Would it be better to list the files into text file and look at that if you were dealing with a lot of searches?
– Mike Q
Jun 13 '14 at 16:35
1
@CostiCiudatu have you checked how that alternative works when there are spaces in the directory name? Wouldn't e.g.for f in /path/to/your files*
interpreted as two arguments,/path/to/your
andfiles*
? I've tried putting double-quotes around, but that didn't work out (never finds a file, even if there's one).
– Izzy
Dec 13 '14 at 21:00
3
@Izzy, you are supposed to put that in double quotes, but leave the*
outside:for f in "/path/to/your files"*
should work.
– Costi Ciudatu
Dec 13 '14 at 23:02
|
show 6 more comments
The simplest should be to rely on ls
return value (it returns non-zero when the files do not exist):
if ls /path/to/your/files* 1> /dev/null 2>&1; then
echo "files do exist"
else
echo "files do not exist"
fi
I redirected the ls
output to make it completely silent.
EDIT: Since this answer has got a bit of attention (and very useful critic remarks as comments), here is an optimization that also relies on glob expansion, but avoids the use of ls
:
for f in /path/to/your/files*; do
## Check if the glob gets expanded to existing files.
## If not, f here will be exactly the pattern above
## and the exists test will evaluate to false.
[ -e "$f" ] && echo "files do exist" || echo "files do not exist"
## This is all we needed to know, so we can break after the first iteration
break
done
This is very similar to @grok12's answer, but it avoids the unnecessary iteration through the whole list.
The simplest should be to rely on ls
return value (it returns non-zero when the files do not exist):
if ls /path/to/your/files* 1> /dev/null 2>&1; then
echo "files do exist"
else
echo "files do not exist"
fi
I redirected the ls
output to make it completely silent.
EDIT: Since this answer has got a bit of attention (and very useful critic remarks as comments), here is an optimization that also relies on glob expansion, but avoids the use of ls
:
for f in /path/to/your/files*; do
## Check if the glob gets expanded to existing files.
## If not, f here will be exactly the pattern above
## and the exists test will evaluate to false.
[ -e "$f" ] && echo "files do exist" || echo "files do not exist"
## This is all we needed to know, so we can break after the first iteration
break
done
This is very similar to @grok12's answer, but it avoids the unnecessary iteration through the whole list.
edited Nov 14 '14 at 16:35
greg0ire
15.8k136088
15.8k136088
answered Jun 15 '11 at 20:56
Costi CiudatuCosti Ciudatu
28.2k54582
28.2k54582
7
A word of warning: In the Debian Almquist Shell (dash
) — installed at/bin/sh
in Debian and Ubuntu —&>
seems to discard the exit code and that breaks this solution. A workaround is to redirect with> /dev/null 2>&1
instead.
– qerub
Nov 20 '11 at 18:42
18
ls
can be quite slow on a directory with many files (probably due to sorting). You may want to turn off sorting with-U
, at least.
– musiphil
Jun 21 '12 at 21:01
Would it be better to list the files into text file and look at that if you were dealing with a lot of searches?
– Mike Q
Jun 13 '14 at 16:35
1
@CostiCiudatu have you checked how that alternative works when there are spaces in the directory name? Wouldn't e.g.for f in /path/to/your files*
interpreted as two arguments,/path/to/your
andfiles*
? I've tried putting double-quotes around, but that didn't work out (never finds a file, even if there's one).
– Izzy
Dec 13 '14 at 21:00
3
@Izzy, you are supposed to put that in double quotes, but leave the*
outside:for f in "/path/to/your files"*
should work.
– Costi Ciudatu
Dec 13 '14 at 23:02
|
show 6 more comments
7
A word of warning: In the Debian Almquist Shell (dash
) — installed at/bin/sh
in Debian and Ubuntu —&>
seems to discard the exit code and that breaks this solution. A workaround is to redirect with> /dev/null 2>&1
instead.
– qerub
Nov 20 '11 at 18:42
18
ls
can be quite slow on a directory with many files (probably due to sorting). You may want to turn off sorting with-U
, at least.
– musiphil
Jun 21 '12 at 21:01
Would it be better to list the files into text file and look at that if you were dealing with a lot of searches?
– Mike Q
Jun 13 '14 at 16:35
1
@CostiCiudatu have you checked how that alternative works when there are spaces in the directory name? Wouldn't e.g.for f in /path/to/your files*
interpreted as two arguments,/path/to/your
andfiles*
? I've tried putting double-quotes around, but that didn't work out (never finds a file, even if there's one).
– Izzy
Dec 13 '14 at 21:00
3
@Izzy, you are supposed to put that in double quotes, but leave the*
outside:for f in "/path/to/your files"*
should work.
– Costi Ciudatu
Dec 13 '14 at 23:02
7
7
A word of warning: In the Debian Almquist Shell (
dash
) — installed at /bin/sh
in Debian and Ubuntu — &>
seems to discard the exit code and that breaks this solution. A workaround is to redirect with > /dev/null 2>&1
instead.– qerub
Nov 20 '11 at 18:42
A word of warning: In the Debian Almquist Shell (
dash
) — installed at /bin/sh
in Debian and Ubuntu — &>
seems to discard the exit code and that breaks this solution. A workaround is to redirect with > /dev/null 2>&1
instead.– qerub
Nov 20 '11 at 18:42
18
18
ls
can be quite slow on a directory with many files (probably due to sorting). You may want to turn off sorting with -U
, at least.– musiphil
Jun 21 '12 at 21:01
ls
can be quite slow on a directory with many files (probably due to sorting). You may want to turn off sorting with -U
, at least.– musiphil
Jun 21 '12 at 21:01
Would it be better to list the files into text file and look at that if you were dealing with a lot of searches?
– Mike Q
Jun 13 '14 at 16:35
Would it be better to list the files into text file and look at that if you were dealing with a lot of searches?
– Mike Q
Jun 13 '14 at 16:35
1
1
@CostiCiudatu have you checked how that alternative works when there are spaces in the directory name? Wouldn't e.g.
for f in /path/to/your files*
interpreted as two arguments, /path/to/your
and files*
? I've tried putting double-quotes around, but that didn't work out (never finds a file, even if there's one).– Izzy
Dec 13 '14 at 21:00
@CostiCiudatu have you checked how that alternative works when there are spaces in the directory name? Wouldn't e.g.
for f in /path/to/your files*
interpreted as two arguments, /path/to/your
and files*
? I've tried putting double-quotes around, but that didn't work out (never finds a file, even if there's one).– Izzy
Dec 13 '14 at 21:00
3
3
@Izzy, you are supposed to put that in double quotes, but leave the
*
outside: for f in "/path/to/your files"*
should work.– Costi Ciudatu
Dec 13 '14 at 23:02
@Izzy, you are supposed to put that in double quotes, but leave the
*
outside: for f in "/path/to/your files"*
should work.– Costi Ciudatu
Dec 13 '14 at 23:02
|
show 6 more comments
If your shell has a nullglob option and it's turned on, a wildcard pattern that matches no files will be removed from the command line altogether. This will make ls see no pathname arguments, list the contents of the current directory and succeed, which is wrong. GNU stat, which always fails if given no arguments or an argument naming a nonexistent file, would be more robust. Also, the &> redirection operator is a bashism.
if stat --printf='' /path/to/your/files* 2>/dev/null
then
echo found
else
echo not found
fi
Better still is GNU find, which can handle a wildcard search internally and exit as soon as at it finds one matching file, rather than waste time processing a potentially huge list of them expanded by the shell; this also avoids the risk that the shell might overflow its command line buffer.
if test -n "$(find /dir/to/search -maxdepth 1 -name 'files*' -print -quit)"
then
echo found
else
echo not found
fi
Non-GNU versions of find might not have the -maxdepth option used here to make find search only the /dir/to/search instead of the entire directory tree rooted there.
6
Lettingfind
handle the wildcard is best becausebash
, as it expands the pattern, tries to sort the list of the matching file names, which is wasteful and can be expensive.
– musiphil
Jun 21 '12 at 21:10
@musiphil Launching an external process such asfind
is even more wasteful if there are only a few files (or none) in the directory.
– dolmen
Feb 24 '17 at 16:46
@dolmen: You are right. I guess it all depends on the situation; on the other hand, if there are a huge number of files, the wildcard expansion ofbash
can take more time than launchingfind
.
– musiphil
Mar 13 '17 at 18:48
@musiphil Even worse: if there is a huge number of the wildcard expansion can simply fail. But in that case, expanding the huge output offind
will probably fail too. Note also that listing all files with find just to then test if that output is empty or not is a big waste of resources.
– dolmen
Apr 13 '17 at 7:41
1
@dolmen: Runningfind
with-quit
as described in @flabdablet's post will not suffer from a huge number of files, because it quits as soon as it finds the first match and thus will not list all files. So it is not as big a waste of resources as you suggest. Moreover,find
doesn't simply "expand" the wildcard as the shell does, but checks each file it finds against the pattern to see if it is a match, so it doesn't fail for a huge number of files.
– musiphil
Apr 25 '17 at 1:34
|
show 1 more comment
If your shell has a nullglob option and it's turned on, a wildcard pattern that matches no files will be removed from the command line altogether. This will make ls see no pathname arguments, list the contents of the current directory and succeed, which is wrong. GNU stat, which always fails if given no arguments or an argument naming a nonexistent file, would be more robust. Also, the &> redirection operator is a bashism.
if stat --printf='' /path/to/your/files* 2>/dev/null
then
echo found
else
echo not found
fi
Better still is GNU find, which can handle a wildcard search internally and exit as soon as at it finds one matching file, rather than waste time processing a potentially huge list of them expanded by the shell; this also avoids the risk that the shell might overflow its command line buffer.
if test -n "$(find /dir/to/search -maxdepth 1 -name 'files*' -print -quit)"
then
echo found
else
echo not found
fi
Non-GNU versions of find might not have the -maxdepth option used here to make find search only the /dir/to/search instead of the entire directory tree rooted there.
6
Lettingfind
handle the wildcard is best becausebash
, as it expands the pattern, tries to sort the list of the matching file names, which is wasteful and can be expensive.
– musiphil
Jun 21 '12 at 21:10
@musiphil Launching an external process such asfind
is even more wasteful if there are only a few files (or none) in the directory.
– dolmen
Feb 24 '17 at 16:46
@dolmen: You are right. I guess it all depends on the situation; on the other hand, if there are a huge number of files, the wildcard expansion ofbash
can take more time than launchingfind
.
– musiphil
Mar 13 '17 at 18:48
@musiphil Even worse: if there is a huge number of the wildcard expansion can simply fail. But in that case, expanding the huge output offind
will probably fail too. Note also that listing all files with find just to then test if that output is empty or not is a big waste of resources.
– dolmen
Apr 13 '17 at 7:41
1
@dolmen: Runningfind
with-quit
as described in @flabdablet's post will not suffer from a huge number of files, because it quits as soon as it finds the first match and thus will not list all files. So it is not as big a waste of resources as you suggest. Moreover,find
doesn't simply "expand" the wildcard as the shell does, but checks each file it finds against the pattern to see if it is a match, so it doesn't fail for a huge number of files.
– musiphil
Apr 25 '17 at 1:34
|
show 1 more comment
If your shell has a nullglob option and it's turned on, a wildcard pattern that matches no files will be removed from the command line altogether. This will make ls see no pathname arguments, list the contents of the current directory and succeed, which is wrong. GNU stat, which always fails if given no arguments or an argument naming a nonexistent file, would be more robust. Also, the &> redirection operator is a bashism.
if stat --printf='' /path/to/your/files* 2>/dev/null
then
echo found
else
echo not found
fi
Better still is GNU find, which can handle a wildcard search internally and exit as soon as at it finds one matching file, rather than waste time processing a potentially huge list of them expanded by the shell; this also avoids the risk that the shell might overflow its command line buffer.
if test -n "$(find /dir/to/search -maxdepth 1 -name 'files*' -print -quit)"
then
echo found
else
echo not found
fi
Non-GNU versions of find might not have the -maxdepth option used here to make find search only the /dir/to/search instead of the entire directory tree rooted there.
If your shell has a nullglob option and it's turned on, a wildcard pattern that matches no files will be removed from the command line altogether. This will make ls see no pathname arguments, list the contents of the current directory and succeed, which is wrong. GNU stat, which always fails if given no arguments or an argument naming a nonexistent file, would be more robust. Also, the &> redirection operator is a bashism.
if stat --printf='' /path/to/your/files* 2>/dev/null
then
echo found
else
echo not found
fi
Better still is GNU find, which can handle a wildcard search internally and exit as soon as at it finds one matching file, rather than waste time processing a potentially huge list of them expanded by the shell; this also avoids the risk that the shell might overflow its command line buffer.
if test -n "$(find /dir/to/search -maxdepth 1 -name 'files*' -print -quit)"
then
echo found
else
echo not found
fi
Non-GNU versions of find might not have the -maxdepth option used here to make find search only the /dir/to/search instead of the entire directory tree rooted there.
answered Oct 9 '11 at 8:33
flabdabletflabdablet
2,50931813
2,50931813
6
Lettingfind
handle the wildcard is best becausebash
, as it expands the pattern, tries to sort the list of the matching file names, which is wasteful and can be expensive.
– musiphil
Jun 21 '12 at 21:10
@musiphil Launching an external process such asfind
is even more wasteful if there are only a few files (or none) in the directory.
– dolmen
Feb 24 '17 at 16:46
@dolmen: You are right. I guess it all depends on the situation; on the other hand, if there are a huge number of files, the wildcard expansion ofbash
can take more time than launchingfind
.
– musiphil
Mar 13 '17 at 18:48
@musiphil Even worse: if there is a huge number of the wildcard expansion can simply fail. But in that case, expanding the huge output offind
will probably fail too. Note also that listing all files with find just to then test if that output is empty or not is a big waste of resources.
– dolmen
Apr 13 '17 at 7:41
1
@dolmen: Runningfind
with-quit
as described in @flabdablet's post will not suffer from a huge number of files, because it quits as soon as it finds the first match and thus will not list all files. So it is not as big a waste of resources as you suggest. Moreover,find
doesn't simply "expand" the wildcard as the shell does, but checks each file it finds against the pattern to see if it is a match, so it doesn't fail for a huge number of files.
– musiphil
Apr 25 '17 at 1:34
|
show 1 more comment
6
Lettingfind
handle the wildcard is best becausebash
, as it expands the pattern, tries to sort the list of the matching file names, which is wasteful and can be expensive.
– musiphil
Jun 21 '12 at 21:10
@musiphil Launching an external process such asfind
is even more wasteful if there are only a few files (or none) in the directory.
– dolmen
Feb 24 '17 at 16:46
@dolmen: You are right. I guess it all depends on the situation; on the other hand, if there are a huge number of files, the wildcard expansion ofbash
can take more time than launchingfind
.
– musiphil
Mar 13 '17 at 18:48
@musiphil Even worse: if there is a huge number of the wildcard expansion can simply fail. But in that case, expanding the huge output offind
will probably fail too. Note also that listing all files with find just to then test if that output is empty or not is a big waste of resources.
– dolmen
Apr 13 '17 at 7:41
1
@dolmen: Runningfind
with-quit
as described in @flabdablet's post will not suffer from a huge number of files, because it quits as soon as it finds the first match and thus will not list all files. So it is not as big a waste of resources as you suggest. Moreover,find
doesn't simply "expand" the wildcard as the shell does, but checks each file it finds against the pattern to see if it is a match, so it doesn't fail for a huge number of files.
– musiphil
Apr 25 '17 at 1:34
6
6
Letting
find
handle the wildcard is best because bash
, as it expands the pattern, tries to sort the list of the matching file names, which is wasteful and can be expensive.– musiphil
Jun 21 '12 at 21:10
Letting
find
handle the wildcard is best because bash
, as it expands the pattern, tries to sort the list of the matching file names, which is wasteful and can be expensive.– musiphil
Jun 21 '12 at 21:10
@musiphil Launching an external process such as
find
is even more wasteful if there are only a few files (or none) in the directory.– dolmen
Feb 24 '17 at 16:46
@musiphil Launching an external process such as
find
is even more wasteful if there are only a few files (or none) in the directory.– dolmen
Feb 24 '17 at 16:46
@dolmen: You are right. I guess it all depends on the situation; on the other hand, if there are a huge number of files, the wildcard expansion of
bash
can take more time than launching find
.– musiphil
Mar 13 '17 at 18:48
@dolmen: You are right. I guess it all depends on the situation; on the other hand, if there are a huge number of files, the wildcard expansion of
bash
can take more time than launching find
.– musiphil
Mar 13 '17 at 18:48
@musiphil Even worse: if there is a huge number of the wildcard expansion can simply fail. But in that case, expanding the huge output of
find
will probably fail too. Note also that listing all files with find just to then test if that output is empty or not is a big waste of resources.– dolmen
Apr 13 '17 at 7:41
@musiphil Even worse: if there is a huge number of the wildcard expansion can simply fail. But in that case, expanding the huge output of
find
will probably fail too. Note also that listing all files with find just to then test if that output is empty or not is a big waste of resources.– dolmen
Apr 13 '17 at 7:41
1
1
@dolmen: Running
find
with -quit
as described in @flabdablet's post will not suffer from a huge number of files, because it quits as soon as it finds the first match and thus will not list all files. So it is not as big a waste of resources as you suggest. Moreover, find
doesn't simply "expand" the wildcard as the shell does, but checks each file it finds against the pattern to see if it is a match, so it doesn't fail for a huge number of files.– musiphil
Apr 25 '17 at 1:34
@dolmen: Running
find
with -quit
as described in @flabdablet's post will not suffer from a huge number of files, because it quits as soon as it finds the first match and thus will not list all files. So it is not as big a waste of resources as you suggest. Moreover, find
doesn't simply "expand" the wildcard as the shell does, but checks each file it finds against the pattern to see if it is a match, so it doesn't fail for a huge number of files.– musiphil
Apr 25 '17 at 1:34
|
show 1 more comment
Here is my answer -
files=(xorg-x11-fonts*)
if [ -e "${files[0]}" ];
then
printf "BLAH"
fi
You should addunsetopt nomatch
if zsh reports errors.
– Chih-Hsuan Yen
Jan 3 '15 at 9:38
5
andshopt -s nullglob
forbash
– nhed
Jun 27 '16 at 23:28
It shouild perhaps be pointed out more clearly that using an array makes this decidedly non-POSIXsh
.
– tripleee
Sep 26 '17 at 9:11
add a comment |
Here is my answer -
files=(xorg-x11-fonts*)
if [ -e "${files[0]}" ];
then
printf "BLAH"
fi
You should addunsetopt nomatch
if zsh reports errors.
– Chih-Hsuan Yen
Jan 3 '15 at 9:38
5
andshopt -s nullglob
forbash
– nhed
Jun 27 '16 at 23:28
It shouild perhaps be pointed out more clearly that using an array makes this decidedly non-POSIXsh
.
– tripleee
Sep 26 '17 at 9:11
add a comment |
Here is my answer -
files=(xorg-x11-fonts*)
if [ -e "${files[0]}" ];
then
printf "BLAH"
fi
Here is my answer -
files=(xorg-x11-fonts*)
if [ -e "${files[0]}" ];
then
printf "BLAH"
fi
edited Jul 2 '13 at 9:35
answered Jul 1 '13 at 12:45
Pankaj ParasharPankaj Parashar
3,49432538
3,49432538
You should addunsetopt nomatch
if zsh reports errors.
– Chih-Hsuan Yen
Jan 3 '15 at 9:38
5
andshopt -s nullglob
forbash
– nhed
Jun 27 '16 at 23:28
It shouild perhaps be pointed out more clearly that using an array makes this decidedly non-POSIXsh
.
– tripleee
Sep 26 '17 at 9:11
add a comment |
You should addunsetopt nomatch
if zsh reports errors.
– Chih-Hsuan Yen
Jan 3 '15 at 9:38
5
andshopt -s nullglob
forbash
– nhed
Jun 27 '16 at 23:28
It shouild perhaps be pointed out more clearly that using an array makes this decidedly non-POSIXsh
.
– tripleee
Sep 26 '17 at 9:11
You should add
unsetopt nomatch
if zsh reports errors.– Chih-Hsuan Yen
Jan 3 '15 at 9:38
You should add
unsetopt nomatch
if zsh reports errors.– Chih-Hsuan Yen
Jan 3 '15 at 9:38
5
5
and
shopt -s nullglob
for bash
– nhed
Jun 27 '16 at 23:28
and
shopt -s nullglob
for bash
– nhed
Jun 27 '16 at 23:28
It shouild perhaps be pointed out more clearly that using an array makes this decidedly non-POSIX
sh
.– tripleee
Sep 26 '17 at 9:11
It shouild perhaps be pointed out more clearly that using an array makes this decidedly non-POSIX
sh
.– tripleee
Sep 26 '17 at 9:11
add a comment |
for i in xorg-x11-fonts*; do
if [ -f "$i" ]; then printf "BLAH"; fi
done
This will work with multiple files and with white space in file names.
4
It will print multiple "BLAH" if there are multiple matches. Maybe add abreak
to exit the loop after the first match.
– tripleee
May 27 '16 at 18:19
1
This (with @tripleee ‘s break) gets my vote. By using only native globbing and the file test operator, it avoids even raising the question of corner cases, that comes with using commands like ls or find or from forwarding globs. I think it is free of all the issues, like names with blanks, nullglob setting and bashisms, that were raised for some other answers. I made a function of it:existsAnyFile () { for file; do [ -f "$file" ] && return 0; done; false; }
– sdenham
Jun 30 '16 at 15:49
Note this gets a stat failure if xorg-x11-fonts* does not exist, which is probably not what you want.
– rfay
Nov 8 '18 at 23:04
add a comment |
for i in xorg-x11-fonts*; do
if [ -f "$i" ]; then printf "BLAH"; fi
done
This will work with multiple files and with white space in file names.
4
It will print multiple "BLAH" if there are multiple matches. Maybe add abreak
to exit the loop after the first match.
– tripleee
May 27 '16 at 18:19
1
This (with @tripleee ‘s break) gets my vote. By using only native globbing and the file test operator, it avoids even raising the question of corner cases, that comes with using commands like ls or find or from forwarding globs. I think it is free of all the issues, like names with blanks, nullglob setting and bashisms, that were raised for some other answers. I made a function of it:existsAnyFile () { for file; do [ -f "$file" ] && return 0; done; false; }
– sdenham
Jun 30 '16 at 15:49
Note this gets a stat failure if xorg-x11-fonts* does not exist, which is probably not what you want.
– rfay
Nov 8 '18 at 23:04
add a comment |
for i in xorg-x11-fonts*; do
if [ -f "$i" ]; then printf "BLAH"; fi
done
This will work with multiple files and with white space in file names.
for i in xorg-x11-fonts*; do
if [ -f "$i" ]; then printf "BLAH"; fi
done
This will work with multiple files and with white space in file names.
edited May 27 '16 at 18:19
tripleee
94.9k13133188
94.9k13133188
answered Jun 18 '11 at 18:21
grok12grok12
1,48351724
1,48351724
4
It will print multiple "BLAH" if there are multiple matches. Maybe add abreak
to exit the loop after the first match.
– tripleee
May 27 '16 at 18:19
1
This (with @tripleee ‘s break) gets my vote. By using only native globbing and the file test operator, it avoids even raising the question of corner cases, that comes with using commands like ls or find or from forwarding globs. I think it is free of all the issues, like names with blanks, nullglob setting and bashisms, that were raised for some other answers. I made a function of it:existsAnyFile () { for file; do [ -f "$file" ] && return 0; done; false; }
– sdenham
Jun 30 '16 at 15:49
Note this gets a stat failure if xorg-x11-fonts* does not exist, which is probably not what you want.
– rfay
Nov 8 '18 at 23:04
add a comment |
4
It will print multiple "BLAH" if there are multiple matches. Maybe add abreak
to exit the loop after the first match.
– tripleee
May 27 '16 at 18:19
1
This (with @tripleee ‘s break) gets my vote. By using only native globbing and the file test operator, it avoids even raising the question of corner cases, that comes with using commands like ls or find or from forwarding globs. I think it is free of all the issues, like names with blanks, nullglob setting and bashisms, that were raised for some other answers. I made a function of it:existsAnyFile () { for file; do [ -f "$file" ] && return 0; done; false; }
– sdenham
Jun 30 '16 at 15:49
Note this gets a stat failure if xorg-x11-fonts* does not exist, which is probably not what you want.
– rfay
Nov 8 '18 at 23:04
4
4
It will print multiple "BLAH" if there are multiple matches. Maybe add a
break
to exit the loop after the first match.– tripleee
May 27 '16 at 18:19
It will print multiple "BLAH" if there are multiple matches. Maybe add a
break
to exit the loop after the first match.– tripleee
May 27 '16 at 18:19
1
1
This (with @tripleee ‘s break) gets my vote. By using only native globbing and the file test operator, it avoids even raising the question of corner cases, that comes with using commands like ls or find or from forwarding globs. I think it is free of all the issues, like names with blanks, nullglob setting and bashisms, that were raised for some other answers. I made a function of it:
existsAnyFile () { for file; do [ -f "$file" ] && return 0; done; false; }
– sdenham
Jun 30 '16 at 15:49
This (with @tripleee ‘s break) gets my vote. By using only native globbing and the file test operator, it avoids even raising the question of corner cases, that comes with using commands like ls or find or from forwarding globs. I think it is free of all the issues, like names with blanks, nullglob setting and bashisms, that were raised for some other answers. I made a function of it:
existsAnyFile () { for file; do [ -f "$file" ] && return 0; done; false; }
– sdenham
Jun 30 '16 at 15:49
Note this gets a stat failure if xorg-x11-fonts* does not exist, which is probably not what you want.
– rfay
Nov 8 '18 at 23:04
Note this gets a stat failure if xorg-x11-fonts* does not exist, which is probably not what you want.
– rfay
Nov 8 '18 at 23:04
add a comment |
You can do the following:
set -- xorg-x11-fonts*
if [ -f "$1" ]; then
printf "BLAH"
fi
This works with sh and derivates: ksh and bash. It doesn't create any sub-shell. $(..)and `...` commands create a sub-shell : they fork a process, and they are inefficient. Of course it works with several files, and this solution can be the fastest, or second to the fastest one.
It works too when there's no matches. There isn't need to use nullglob as one of the comentatators say. $1 will contain the origintal test name, therefore the test -f $1 won't success, because the $1 file doesn't exist.
The most portable solution!
– dolmen
Feb 24 '17 at 17:03
1
Alas, it doesn't work when there's no matches. $1 will contain the original test name, including the *. You could set "nullglob" in bash so it WILL blank out. THat's not portable, though :)
– Chris Cogdon
Mar 9 '18 at 20:55
Chris, when there isn't a match, $1 will contain the origintal test name, including the * as you say. Then the test: [ -f "$1" ] won't be sucessfull because the file "*" doesn't exist. Therefore you don't need nullglob, or other tricks. It is 100% portable.
– joseyluis
May 16 '18 at 9:59
add a comment |
You can do the following:
set -- xorg-x11-fonts*
if [ -f "$1" ]; then
printf "BLAH"
fi
This works with sh and derivates: ksh and bash. It doesn't create any sub-shell. $(..)and `...` commands create a sub-shell : they fork a process, and they are inefficient. Of course it works with several files, and this solution can be the fastest, or second to the fastest one.
It works too when there's no matches. There isn't need to use nullglob as one of the comentatators say. $1 will contain the origintal test name, therefore the test -f $1 won't success, because the $1 file doesn't exist.
The most portable solution!
– dolmen
Feb 24 '17 at 17:03
1
Alas, it doesn't work when there's no matches. $1 will contain the original test name, including the *. You could set "nullglob" in bash so it WILL blank out. THat's not portable, though :)
– Chris Cogdon
Mar 9 '18 at 20:55
Chris, when there isn't a match, $1 will contain the origintal test name, including the * as you say. Then the test: [ -f "$1" ] won't be sucessfull because the file "*" doesn't exist. Therefore you don't need nullglob, or other tricks. It is 100% portable.
– joseyluis
May 16 '18 at 9:59
add a comment |
You can do the following:
set -- xorg-x11-fonts*
if [ -f "$1" ]; then
printf "BLAH"
fi
This works with sh and derivates: ksh and bash. It doesn't create any sub-shell. $(..)and `...` commands create a sub-shell : they fork a process, and they are inefficient. Of course it works with several files, and this solution can be the fastest, or second to the fastest one.
It works too when there's no matches. There isn't need to use nullglob as one of the comentatators say. $1 will contain the origintal test name, therefore the test -f $1 won't success, because the $1 file doesn't exist.
You can do the following:
set -- xorg-x11-fonts*
if [ -f "$1" ]; then
printf "BLAH"
fi
This works with sh and derivates: ksh and bash. It doesn't create any sub-shell. $(..)and `...` commands create a sub-shell : they fork a process, and they are inefficient. Of course it works with several files, and this solution can be the fastest, or second to the fastest one.
It works too when there's no matches. There isn't need to use nullglob as one of the comentatators say. $1 will contain the origintal test name, therefore the test -f $1 won't success, because the $1 file doesn't exist.
edited Sep 3 '18 at 8:07
answered Dec 22 '16 at 11:09
joseyluisjoseyluis
30026
30026
The most portable solution!
– dolmen
Feb 24 '17 at 17:03
1
Alas, it doesn't work when there's no matches. $1 will contain the original test name, including the *. You could set "nullglob" in bash so it WILL blank out. THat's not portable, though :)
– Chris Cogdon
Mar 9 '18 at 20:55
Chris, when there isn't a match, $1 will contain the origintal test name, including the * as you say. Then the test: [ -f "$1" ] won't be sucessfull because the file "*" doesn't exist. Therefore you don't need nullglob, or other tricks. It is 100% portable.
– joseyluis
May 16 '18 at 9:59
add a comment |
The most portable solution!
– dolmen
Feb 24 '17 at 17:03
1
Alas, it doesn't work when there's no matches. $1 will contain the original test name, including the *. You could set "nullglob" in bash so it WILL blank out. THat's not portable, though :)
– Chris Cogdon
Mar 9 '18 at 20:55
Chris, when there isn't a match, $1 will contain the origintal test name, including the * as you say. Then the test: [ -f "$1" ] won't be sucessfull because the file "*" doesn't exist. Therefore you don't need nullglob, or other tricks. It is 100% portable.
– joseyluis
May 16 '18 at 9:59
The most portable solution!
– dolmen
Feb 24 '17 at 17:03
The most portable solution!
– dolmen
Feb 24 '17 at 17:03
1
1
Alas, it doesn't work when there's no matches. $1 will contain the original test name, including the *. You could set "nullglob" in bash so it WILL blank out. THat's not portable, though :)
– Chris Cogdon
Mar 9 '18 at 20:55
Alas, it doesn't work when there's no matches. $1 will contain the original test name, including the *. You could set "nullglob" in bash so it WILL blank out. THat's not portable, though :)
– Chris Cogdon
Mar 9 '18 at 20:55
Chris, when there isn't a match, $1 will contain the origintal test name, including the * as you say. Then the test: [ -f "$1" ] won't be sucessfull because the file "*" doesn't exist. Therefore you don't need nullglob, or other tricks. It is 100% portable.
– joseyluis
May 16 '18 at 9:59
Chris, when there isn't a match, $1 will contain the origintal test name, including the * as you say. Then the test: [ -f "$1" ] won't be sucessfull because the file "*" doesn't exist. Therefore you don't need nullglob, or other tricks. It is 100% portable.
– joseyluis
May 16 '18 at 9:59
add a comment |
UPDATE:
Okay, now I definitely have the solution:
files=$(ls xorg-x11-fonts* 2> /dev/null | wc -l)
if [ "$files" != "0" ]
then
echo "Exists"
else
echo "None found."
fi
> Exists
In my shell (zsh) it works if there is only one match to the glob, otherwise it expands all the files and the test fails (too many arguments.)
– Edward Thomson
Jun 15 '11 at 20:02
Update my code. I'm sure this works, I just installed zsh and tested.
– Swift
Jun 15 '11 at 20:20
Reupdated. My bad.
– Swift
Jun 15 '11 at 20:33
1
ls
can be quite slow on a directory with many files (probably due to sorting). You may want to turn off sorting with-U
, at least.
– musiphil
Jun 21 '12 at 21:01
If the globbing matches a directory name, ls will spit out the contentes of that directory which may cause false positives.
– William Everett
Mar 21 '16 at 22:00
|
show 1 more comment
UPDATE:
Okay, now I definitely have the solution:
files=$(ls xorg-x11-fonts* 2> /dev/null | wc -l)
if [ "$files" != "0" ]
then
echo "Exists"
else
echo "None found."
fi
> Exists
In my shell (zsh) it works if there is only one match to the glob, otherwise it expands all the files and the test fails (too many arguments.)
– Edward Thomson
Jun 15 '11 at 20:02
Update my code. I'm sure this works, I just installed zsh and tested.
– Swift
Jun 15 '11 at 20:20
Reupdated. My bad.
– Swift
Jun 15 '11 at 20:33
1
ls
can be quite slow on a directory with many files (probably due to sorting). You may want to turn off sorting with-U
, at least.
– musiphil
Jun 21 '12 at 21:01
If the globbing matches a directory name, ls will spit out the contentes of that directory which may cause false positives.
– William Everett
Mar 21 '16 at 22:00
|
show 1 more comment
UPDATE:
Okay, now I definitely have the solution:
files=$(ls xorg-x11-fonts* 2> /dev/null | wc -l)
if [ "$files" != "0" ]
then
echo "Exists"
else
echo "None found."
fi
> Exists
UPDATE:
Okay, now I definitely have the solution:
files=$(ls xorg-x11-fonts* 2> /dev/null | wc -l)
if [ "$files" != "0" ]
then
echo "Exists"
else
echo "None found."
fi
> Exists
edited Jun 15 '11 at 20:30
answered Jun 15 '11 at 19:53
SwiftSwift
10.7k44774
10.7k44774
In my shell (zsh) it works if there is only one match to the glob, otherwise it expands all the files and the test fails (too many arguments.)
– Edward Thomson
Jun 15 '11 at 20:02
Update my code. I'm sure this works, I just installed zsh and tested.
– Swift
Jun 15 '11 at 20:20
Reupdated. My bad.
– Swift
Jun 15 '11 at 20:33
1
ls
can be quite slow on a directory with many files (probably due to sorting). You may want to turn off sorting with-U
, at least.
– musiphil
Jun 21 '12 at 21:01
If the globbing matches a directory name, ls will spit out the contentes of that directory which may cause false positives.
– William Everett
Mar 21 '16 at 22:00
|
show 1 more comment
In my shell (zsh) it works if there is only one match to the glob, otherwise it expands all the files and the test fails (too many arguments.)
– Edward Thomson
Jun 15 '11 at 20:02
Update my code. I'm sure this works, I just installed zsh and tested.
– Swift
Jun 15 '11 at 20:20
Reupdated. My bad.
– Swift
Jun 15 '11 at 20:33
1
ls
can be quite slow on a directory with many files (probably due to sorting). You may want to turn off sorting with-U
, at least.
– musiphil
Jun 21 '12 at 21:01
If the globbing matches a directory name, ls will spit out the contentes of that directory which may cause false positives.
– William Everett
Mar 21 '16 at 22:00
In my shell (zsh) it works if there is only one match to the glob, otherwise it expands all the files and the test fails (too many arguments.)
– Edward Thomson
Jun 15 '11 at 20:02
In my shell (zsh) it works if there is only one match to the glob, otherwise it expands all the files and the test fails (too many arguments.)
– Edward Thomson
Jun 15 '11 at 20:02
Update my code. I'm sure this works, I just installed zsh and tested.
– Swift
Jun 15 '11 at 20:20
Update my code. I'm sure this works, I just installed zsh and tested.
– Swift
Jun 15 '11 at 20:20
Reupdated. My bad.
– Swift
Jun 15 '11 at 20:33
Reupdated. My bad.
– Swift
Jun 15 '11 at 20:33
1
1
ls
can be quite slow on a directory with many files (probably due to sorting). You may want to turn off sorting with -U
, at least.– musiphil
Jun 21 '12 at 21:01
ls
can be quite slow on a directory with many files (probably due to sorting). You may want to turn off sorting with -U
, at least.– musiphil
Jun 21 '12 at 21:01
If the globbing matches a directory name, ls will spit out the contentes of that directory which may cause false positives.
– William Everett
Mar 21 '16 at 22:00
If the globbing matches a directory name, ls will spit out the contentes of that directory which may cause false positives.
– William Everett
Mar 21 '16 at 22:00
|
show 1 more comment
Maybe this will help someone:
if [ "`echo xorg-x11-fonts*`" != "xorg-x11-fonts*" ]; then
printf "BLAH"
fi
1
This is the simplest, easiest and most elegant answer that actually works!
– Serge Stroobandt
Jun 28 '15 at 14:00
2
@SergeStroobandt Not sure I agree. The command substitution may be necessary here, but it tickles my cringe reflex.
– tripleee
May 27 '16 at 18:21
2
yea... like what if the file with the literal namexorg-x11-fonts*
exists?
– mlathe
Oct 12 '16 at 18:32
2
Not elegant at all because it forks a sub shell to run the echo command.
– dolmen
Feb 24 '17 at 16:52
1
not elegant, ugly AF
– nhed
Sep 11 '17 at 15:18
add a comment |
Maybe this will help someone:
if [ "`echo xorg-x11-fonts*`" != "xorg-x11-fonts*" ]; then
printf "BLAH"
fi
1
This is the simplest, easiest and most elegant answer that actually works!
– Serge Stroobandt
Jun 28 '15 at 14:00
2
@SergeStroobandt Not sure I agree. The command substitution may be necessary here, but it tickles my cringe reflex.
– tripleee
May 27 '16 at 18:21
2
yea... like what if the file with the literal namexorg-x11-fonts*
exists?
– mlathe
Oct 12 '16 at 18:32
2
Not elegant at all because it forks a sub shell to run the echo command.
– dolmen
Feb 24 '17 at 16:52
1
not elegant, ugly AF
– nhed
Sep 11 '17 at 15:18
add a comment |
Maybe this will help someone:
if [ "`echo xorg-x11-fonts*`" != "xorg-x11-fonts*" ]; then
printf "BLAH"
fi
Maybe this will help someone:
if [ "`echo xorg-x11-fonts*`" != "xorg-x11-fonts*" ]; then
printf "BLAH"
fi
edited Jan 7 '14 at 16:54
answered Jan 7 '14 at 16:48
MarianMarian
6,19711529
6,19711529
1
This is the simplest, easiest and most elegant answer that actually works!
– Serge Stroobandt
Jun 28 '15 at 14:00
2
@SergeStroobandt Not sure I agree. The command substitution may be necessary here, but it tickles my cringe reflex.
– tripleee
May 27 '16 at 18:21
2
yea... like what if the file with the literal namexorg-x11-fonts*
exists?
– mlathe
Oct 12 '16 at 18:32
2
Not elegant at all because it forks a sub shell to run the echo command.
– dolmen
Feb 24 '17 at 16:52
1
not elegant, ugly AF
– nhed
Sep 11 '17 at 15:18
add a comment |
1
This is the simplest, easiest and most elegant answer that actually works!
– Serge Stroobandt
Jun 28 '15 at 14:00
2
@SergeStroobandt Not sure I agree. The command substitution may be necessary here, but it tickles my cringe reflex.
– tripleee
May 27 '16 at 18:21
2
yea... like what if the file with the literal namexorg-x11-fonts*
exists?
– mlathe
Oct 12 '16 at 18:32
2
Not elegant at all because it forks a sub shell to run the echo command.
– dolmen
Feb 24 '17 at 16:52
1
not elegant, ugly AF
– nhed
Sep 11 '17 at 15:18
1
1
This is the simplest, easiest and most elegant answer that actually works!
– Serge Stroobandt
Jun 28 '15 at 14:00
This is the simplest, easiest and most elegant answer that actually works!
– Serge Stroobandt
Jun 28 '15 at 14:00
2
2
@SergeStroobandt Not sure I agree. The command substitution may be necessary here, but it tickles my cringe reflex.
– tripleee
May 27 '16 at 18:21
@SergeStroobandt Not sure I agree. The command substitution may be necessary here, but it tickles my cringe reflex.
– tripleee
May 27 '16 at 18:21
2
2
yea... like what if the file with the literal name
xorg-x11-fonts*
exists?– mlathe
Oct 12 '16 at 18:32
yea... like what if the file with the literal name
xorg-x11-fonts*
exists?– mlathe
Oct 12 '16 at 18:32
2
2
Not elegant at all because it forks a sub shell to run the echo command.
– dolmen
Feb 24 '17 at 16:52
Not elegant at all because it forks a sub shell to run the echo command.
– dolmen
Feb 24 '17 at 16:52
1
1
not elegant, ugly AF
– nhed
Sep 11 '17 at 15:18
not elegant, ugly AF
– nhed
Sep 11 '17 at 15:18
add a comment |
The question wasn't specific to Linux/Bash so I thought I would add the Powershell way - which treats wildcards different - you put it in the quotes like so below:
If (Test-Path "./output/test-pdf-docx/Text-Book-Part-I*"){
Remove-Item -force -v -path ./output/test-pdf-docx/*.pdf
Remove-Item -force -v -path ./output/test-pdf-docx/*.docx
}
I think this is helpful because the concept of the original question covers "shells" in general not just Bash or Linux, and would apply to Powershell users with the same question too.
add a comment |
The question wasn't specific to Linux/Bash so I thought I would add the Powershell way - which treats wildcards different - you put it in the quotes like so below:
If (Test-Path "./output/test-pdf-docx/Text-Book-Part-I*"){
Remove-Item -force -v -path ./output/test-pdf-docx/*.pdf
Remove-Item -force -v -path ./output/test-pdf-docx/*.docx
}
I think this is helpful because the concept of the original question covers "shells" in general not just Bash or Linux, and would apply to Powershell users with the same question too.
add a comment |
The question wasn't specific to Linux/Bash so I thought I would add the Powershell way - which treats wildcards different - you put it in the quotes like so below:
If (Test-Path "./output/test-pdf-docx/Text-Book-Part-I*"){
Remove-Item -force -v -path ./output/test-pdf-docx/*.pdf
Remove-Item -force -v -path ./output/test-pdf-docx/*.docx
}
I think this is helpful because the concept of the original question covers "shells" in general not just Bash or Linux, and would apply to Powershell users with the same question too.
The question wasn't specific to Linux/Bash so I thought I would add the Powershell way - which treats wildcards different - you put it in the quotes like so below:
If (Test-Path "./output/test-pdf-docx/Text-Book-Part-I*"){
Remove-Item -force -v -path ./output/test-pdf-docx/*.pdf
Remove-Item -force -v -path ./output/test-pdf-docx/*.docx
}
I think this is helpful because the concept of the original question covers "shells" in general not just Bash or Linux, and would apply to Powershell users with the same question too.
answered Sep 13 '15 at 2:41
Jeremy HajekJeremy Hajek
1681311
1681311
add a comment |
add a comment |
Strictly speaking, if you only want to print "Blah" here is the solution :
find . -maxdepth 1 -name 'xorg-x11-fonts*' -printf 'BLAH' -quit
Here is another way :
doesFirstFileExist(){
test -e "$1"
}
if doesFirstFileExist xorg-x11-fonts*
then printf "BLAH"
fi
But I think the most optimal is as follow, because it won't try to sort file names :
if [ -z `find . -maxdepth 1 -name 'xorg-x11-fonts*' -printf 1 -quit` ]
then printf "BLAH"
fi
You can also use-exec
option of find like this:find . -maxdepth 1 -name '*.o' -exec rm {} ;
– user3405291
Mar 14 '18 at 7:49
add a comment |
Strictly speaking, if you only want to print "Blah" here is the solution :
find . -maxdepth 1 -name 'xorg-x11-fonts*' -printf 'BLAH' -quit
Here is another way :
doesFirstFileExist(){
test -e "$1"
}
if doesFirstFileExist xorg-x11-fonts*
then printf "BLAH"
fi
But I think the most optimal is as follow, because it won't try to sort file names :
if [ -z `find . -maxdepth 1 -name 'xorg-x11-fonts*' -printf 1 -quit` ]
then printf "BLAH"
fi
You can also use-exec
option of find like this:find . -maxdepth 1 -name '*.o' -exec rm {} ;
– user3405291
Mar 14 '18 at 7:49
add a comment |
Strictly speaking, if you only want to print "Blah" here is the solution :
find . -maxdepth 1 -name 'xorg-x11-fonts*' -printf 'BLAH' -quit
Here is another way :
doesFirstFileExist(){
test -e "$1"
}
if doesFirstFileExist xorg-x11-fonts*
then printf "BLAH"
fi
But I think the most optimal is as follow, because it won't try to sort file names :
if [ -z `find . -maxdepth 1 -name 'xorg-x11-fonts*' -printf 1 -quit` ]
then printf "BLAH"
fi
Strictly speaking, if you only want to print "Blah" here is the solution :
find . -maxdepth 1 -name 'xorg-x11-fonts*' -printf 'BLAH' -quit
Here is another way :
doesFirstFileExist(){
test -e "$1"
}
if doesFirstFileExist xorg-x11-fonts*
then printf "BLAH"
fi
But I think the most optimal is as follow, because it won't try to sort file names :
if [ -z `find . -maxdepth 1 -name 'xorg-x11-fonts*' -printf 1 -quit` ]
then printf "BLAH"
fi
answered Oct 26 '16 at 13:04
VouzeVouze
1,00099
1,00099
You can also use-exec
option of find like this:find . -maxdepth 1 -name '*.o' -exec rm {} ;
– user3405291
Mar 14 '18 at 7:49
add a comment |
You can also use-exec
option of find like this:find . -maxdepth 1 -name '*.o' -exec rm {} ;
– user3405291
Mar 14 '18 at 7:49
You can also use
-exec
option of find like this: find . -maxdepth 1 -name '*.o' -exec rm {} ;
– user3405291
Mar 14 '18 at 7:49
You can also use
-exec
option of find like this: find . -maxdepth 1 -name '*.o' -exec rm {} ;
– user3405291
Mar 14 '18 at 7:49
add a comment |
The bash code I use
if ls /syslog/*.log > /dev/null 2>&1; then
echo "Log files are present in /syslog/;
fi
Thanks!
add a comment |
The bash code I use
if ls /syslog/*.log > /dev/null 2>&1; then
echo "Log files are present in /syslog/;
fi
Thanks!
add a comment |
The bash code I use
if ls /syslog/*.log > /dev/null 2>&1; then
echo "Log files are present in /syslog/;
fi
Thanks!
The bash code I use
if ls /syslog/*.log > /dev/null 2>&1; then
echo "Log files are present in /syslog/;
fi
Thanks!
answered Apr 12 '16 at 18:34
CapitanBlackCapitanBlack
312
312
add a comment |
add a comment |
Here's a solution for your specific problem that doesn't require for
loops or external commands like ls
, find
and the like.
if [ "$(echo xorg-x11-fonts*)" != "xorg-x11-fonts*" ]; then
printf "BLAH"
fi
As you can see, it's just a tad more complicated than what you were hoping for, and relies on the fact that if the shell is not able to expand the glob, it means no files with that glob exist and echo
will output the glob as is, which allows us to do a mere string comparison to check whether any of those files exist at all.
If we were to generalize the procedure, though, we should take into account the fact that files might contain spaces within their names and/or paths and that the glob char could rightfully expand to nothing (in your example, that would be the case of a file whose name is exactly xorg-x11-fonts).
This could be achieved by the following function, in bash.
function doesAnyFileExist {
local arg="$*"
local files=($arg)
[ ${#files[@]} -gt 1 ] || [ ${#files[@]} -eq 1 ] && [ -e "${files[0]}" ]
}
Going back to your example, it could be invoked like this.
if doesAnyFileExist "xorg-x11-fonts*"; then
printf "BLAH"
fi
Glob expansion should happen within the function itself for it to work properly, that's why I put the argument in quotes and that's what the first line in the function body is there for: so that any multiple arguments (which could be the result of a glob expansion outside the function, as well as a spurious parameter) would be coalesced into one. Another approach could be to raise an error if there's more than one argument, yet another could be to ignore all but the 1st argument.
The second line in the function body sets the files
var to an array constituted by all the file names that the glob expanded to, one for each array element. It's fine if the file names contain spaces, each array element will contain the names as is, including the spaces.
The third line in the function body does two things:
It first checks whether there's more than one element in the array. If so, it means the glob surely got expanded to something (due to what we did on the 1st line), which in turn implies that at least one file matching the glob exist, which is all we wanted to know.
If at step 1. we discovered that we got less than 2 elements in the array, then we check whether we got one and if so we check whether that one exist, the usual way. We need to do this extra check in order to account for function arguments without glob chars, in which case the array contains only one, unexpanded, element.
1
This is inefficient because$(..)
launches a sub-shell.
– dolmen
Feb 24 '17 at 16:59
@dolmen a sub-shell is just a process like any other. The accepted answer launches thels
command, which for all intent and purposes is as efficient (or inefficient) as a sub-shell is.
– Fabio A.
Mar 28 '17 at 9:31
I've never written that the accepted answer is better and that I would have accepted if I had been the submitter.
– dolmen
Apr 13 '17 at 7:34
Notice that the generalized method I explain in this very same answer doesn't use any subshell at all.
– Fabio A.
Apr 13 '17 at 11:21
add a comment |
Here's a solution for your specific problem that doesn't require for
loops or external commands like ls
, find
and the like.
if [ "$(echo xorg-x11-fonts*)" != "xorg-x11-fonts*" ]; then
printf "BLAH"
fi
As you can see, it's just a tad more complicated than what you were hoping for, and relies on the fact that if the shell is not able to expand the glob, it means no files with that glob exist and echo
will output the glob as is, which allows us to do a mere string comparison to check whether any of those files exist at all.
If we were to generalize the procedure, though, we should take into account the fact that files might contain spaces within their names and/or paths and that the glob char could rightfully expand to nothing (in your example, that would be the case of a file whose name is exactly xorg-x11-fonts).
This could be achieved by the following function, in bash.
function doesAnyFileExist {
local arg="$*"
local files=($arg)
[ ${#files[@]} -gt 1 ] || [ ${#files[@]} -eq 1 ] && [ -e "${files[0]}" ]
}
Going back to your example, it could be invoked like this.
if doesAnyFileExist "xorg-x11-fonts*"; then
printf "BLAH"
fi
Glob expansion should happen within the function itself for it to work properly, that's why I put the argument in quotes and that's what the first line in the function body is there for: so that any multiple arguments (which could be the result of a glob expansion outside the function, as well as a spurious parameter) would be coalesced into one. Another approach could be to raise an error if there's more than one argument, yet another could be to ignore all but the 1st argument.
The second line in the function body sets the files
var to an array constituted by all the file names that the glob expanded to, one for each array element. It's fine if the file names contain spaces, each array element will contain the names as is, including the spaces.
The third line in the function body does two things:
It first checks whether there's more than one element in the array. If so, it means the glob surely got expanded to something (due to what we did on the 1st line), which in turn implies that at least one file matching the glob exist, which is all we wanted to know.
If at step 1. we discovered that we got less than 2 elements in the array, then we check whether we got one and if so we check whether that one exist, the usual way. We need to do this extra check in order to account for function arguments without glob chars, in which case the array contains only one, unexpanded, element.
1
This is inefficient because$(..)
launches a sub-shell.
– dolmen
Feb 24 '17 at 16:59
@dolmen a sub-shell is just a process like any other. The accepted answer launches thels
command, which for all intent and purposes is as efficient (or inefficient) as a sub-shell is.
– Fabio A.
Mar 28 '17 at 9:31
I've never written that the accepted answer is better and that I would have accepted if I had been the submitter.
– dolmen
Apr 13 '17 at 7:34
Notice that the generalized method I explain in this very same answer doesn't use any subshell at all.
– Fabio A.
Apr 13 '17 at 11:21
add a comment |
Here's a solution for your specific problem that doesn't require for
loops or external commands like ls
, find
and the like.
if [ "$(echo xorg-x11-fonts*)" != "xorg-x11-fonts*" ]; then
printf "BLAH"
fi
As you can see, it's just a tad more complicated than what you were hoping for, and relies on the fact that if the shell is not able to expand the glob, it means no files with that glob exist and echo
will output the glob as is, which allows us to do a mere string comparison to check whether any of those files exist at all.
If we were to generalize the procedure, though, we should take into account the fact that files might contain spaces within their names and/or paths and that the glob char could rightfully expand to nothing (in your example, that would be the case of a file whose name is exactly xorg-x11-fonts).
This could be achieved by the following function, in bash.
function doesAnyFileExist {
local arg="$*"
local files=($arg)
[ ${#files[@]} -gt 1 ] || [ ${#files[@]} -eq 1 ] && [ -e "${files[0]}" ]
}
Going back to your example, it could be invoked like this.
if doesAnyFileExist "xorg-x11-fonts*"; then
printf "BLAH"
fi
Glob expansion should happen within the function itself for it to work properly, that's why I put the argument in quotes and that's what the first line in the function body is there for: so that any multiple arguments (which could be the result of a glob expansion outside the function, as well as a spurious parameter) would be coalesced into one. Another approach could be to raise an error if there's more than one argument, yet another could be to ignore all but the 1st argument.
The second line in the function body sets the files
var to an array constituted by all the file names that the glob expanded to, one for each array element. It's fine if the file names contain spaces, each array element will contain the names as is, including the spaces.
The third line in the function body does two things:
It first checks whether there's more than one element in the array. If so, it means the glob surely got expanded to something (due to what we did on the 1st line), which in turn implies that at least one file matching the glob exist, which is all we wanted to know.
If at step 1. we discovered that we got less than 2 elements in the array, then we check whether we got one and if so we check whether that one exist, the usual way. We need to do this extra check in order to account for function arguments without glob chars, in which case the array contains only one, unexpanded, element.
Here's a solution for your specific problem that doesn't require for
loops or external commands like ls
, find
and the like.
if [ "$(echo xorg-x11-fonts*)" != "xorg-x11-fonts*" ]; then
printf "BLAH"
fi
As you can see, it's just a tad more complicated than what you were hoping for, and relies on the fact that if the shell is not able to expand the glob, it means no files with that glob exist and echo
will output the glob as is, which allows us to do a mere string comparison to check whether any of those files exist at all.
If we were to generalize the procedure, though, we should take into account the fact that files might contain spaces within their names and/or paths and that the glob char could rightfully expand to nothing (in your example, that would be the case of a file whose name is exactly xorg-x11-fonts).
This could be achieved by the following function, in bash.
function doesAnyFileExist {
local arg="$*"
local files=($arg)
[ ${#files[@]} -gt 1 ] || [ ${#files[@]} -eq 1 ] && [ -e "${files[0]}" ]
}
Going back to your example, it could be invoked like this.
if doesAnyFileExist "xorg-x11-fonts*"; then
printf "BLAH"
fi
Glob expansion should happen within the function itself for it to work properly, that's why I put the argument in quotes and that's what the first line in the function body is there for: so that any multiple arguments (which could be the result of a glob expansion outside the function, as well as a spurious parameter) would be coalesced into one. Another approach could be to raise an error if there's more than one argument, yet another could be to ignore all but the 1st argument.
The second line in the function body sets the files
var to an array constituted by all the file names that the glob expanded to, one for each array element. It's fine if the file names contain spaces, each array element will contain the names as is, including the spaces.
The third line in the function body does two things:
It first checks whether there's more than one element in the array. If so, it means the glob surely got expanded to something (due to what we did on the 1st line), which in turn implies that at least one file matching the glob exist, which is all we wanted to know.
If at step 1. we discovered that we got less than 2 elements in the array, then we check whether we got one and if so we check whether that one exist, the usual way. We need to do this extra check in order to account for function arguments without glob chars, in which case the array contains only one, unexpanded, element.
answered Nov 25 '16 at 15:32
Fabio A.Fabio A.
793719
793719
1
This is inefficient because$(..)
launches a sub-shell.
– dolmen
Feb 24 '17 at 16:59
@dolmen a sub-shell is just a process like any other. The accepted answer launches thels
command, which for all intent and purposes is as efficient (or inefficient) as a sub-shell is.
– Fabio A.
Mar 28 '17 at 9:31
I've never written that the accepted answer is better and that I would have accepted if I had been the submitter.
– dolmen
Apr 13 '17 at 7:34
Notice that the generalized method I explain in this very same answer doesn't use any subshell at all.
– Fabio A.
Apr 13 '17 at 11:21
add a comment |
1
This is inefficient because$(..)
launches a sub-shell.
– dolmen
Feb 24 '17 at 16:59
@dolmen a sub-shell is just a process like any other. The accepted answer launches thels
command, which for all intent and purposes is as efficient (or inefficient) as a sub-shell is.
– Fabio A.
Mar 28 '17 at 9:31
I've never written that the accepted answer is better and that I would have accepted if I had been the submitter.
– dolmen
Apr 13 '17 at 7:34
Notice that the generalized method I explain in this very same answer doesn't use any subshell at all.
– Fabio A.
Apr 13 '17 at 11:21
1
1
This is inefficient because
$(..)
launches a sub-shell.– dolmen
Feb 24 '17 at 16:59
This is inefficient because
$(..)
launches a sub-shell.– dolmen
Feb 24 '17 at 16:59
@dolmen a sub-shell is just a process like any other. The accepted answer launches the
ls
command, which for all intent and purposes is as efficient (or inefficient) as a sub-shell is.– Fabio A.
Mar 28 '17 at 9:31
@dolmen a sub-shell is just a process like any other. The accepted answer launches the
ls
command, which for all intent and purposes is as efficient (or inefficient) as a sub-shell is.– Fabio A.
Mar 28 '17 at 9:31
I've never written that the accepted answer is better and that I would have accepted if I had been the submitter.
– dolmen
Apr 13 '17 at 7:34
I've never written that the accepted answer is better and that I would have accepted if I had been the submitter.
– dolmen
Apr 13 '17 at 7:34
Notice that the generalized method I explain in this very same answer doesn't use any subshell at all.
– Fabio A.
Apr 13 '17 at 11:21
Notice that the generalized method I explain in this very same answer doesn't use any subshell at all.
– Fabio A.
Apr 13 '17 at 11:21
add a comment |
I use this:
filescount=`ls xorg-x11-fonts* | awk 'END { print NR }'`
if [ $filescount -gt 0 ]; then
blah
fi
2
wc -l
is more efficient thanawk
for this task.
– dolmen
Feb 24 '17 at 16:57
1
Counting the number of results is an antipattern anyway. Usually you simply want to see whetherls
returned success or not (or better yet avoidls
too and use the shell's built-in functionality).
– tripleee
Sep 26 '17 at 9:10
add a comment |
I use this:
filescount=`ls xorg-x11-fonts* | awk 'END { print NR }'`
if [ $filescount -gt 0 ]; then
blah
fi
2
wc -l
is more efficient thanawk
for this task.
– dolmen
Feb 24 '17 at 16:57
1
Counting the number of results is an antipattern anyway. Usually you simply want to see whetherls
returned success or not (or better yet avoidls
too and use the shell's built-in functionality).
– tripleee
Sep 26 '17 at 9:10
add a comment |
I use this:
filescount=`ls xorg-x11-fonts* | awk 'END { print NR }'`
if [ $filescount -gt 0 ]; then
blah
fi
I use this:
filescount=`ls xorg-x11-fonts* | awk 'END { print NR }'`
if [ $filescount -gt 0 ]; then
blah
fi
answered Oct 21 '14 at 18:59
Alexandre Vr.Alexandre Vr.
191
191
2
wc -l
is more efficient thanawk
for this task.
– dolmen
Feb 24 '17 at 16:57
1
Counting the number of results is an antipattern anyway. Usually you simply want to see whetherls
returned success or not (or better yet avoidls
too and use the shell's built-in functionality).
– tripleee
Sep 26 '17 at 9:10
add a comment |
2
wc -l
is more efficient thanawk
for this task.
– dolmen
Feb 24 '17 at 16:57
1
Counting the number of results is an antipattern anyway. Usually you simply want to see whetherls
returned success or not (or better yet avoidls
too and use the shell's built-in functionality).
– tripleee
Sep 26 '17 at 9:10
2
2
wc -l
is more efficient than awk
for this task.– dolmen
Feb 24 '17 at 16:57
wc -l
is more efficient than awk
for this task.– dolmen
Feb 24 '17 at 16:57
1
1
Counting the number of results is an antipattern anyway. Usually you simply want to see whether
ls
returned success or not (or better yet avoid ls
too and use the shell's built-in functionality).– tripleee
Sep 26 '17 at 9:10
Counting the number of results is an antipattern anyway. Usually you simply want to see whether
ls
returned success or not (or better yet avoid ls
too and use the shell's built-in functionality).– tripleee
Sep 26 '17 at 9:10
add a comment |
IMHO it's better to use find
always when testing for files, globs or directories. The stumbling block in doing so is find
's exit status: 0 if all paths were traversed successfully, >0 otherwise. The expression you passed to find
creates no echo in its exit code.
The following example tests if a directory has entries:
$ mkdir A
$ touch A/b
$ find A -maxdepth 0 -not -empty -print | head -n1 | grep -q . && echo 'not empty'
not empty
When A
has no files grep
fails:
$ rm A/b
$ find A -maxdepth 0 -not -empty -print | head -n1 | grep -q . || echo 'empty'
empty
When A
does not exist grep
fails again because find
only prints to stderr:
$ rmdir A
$ find A -maxdepth 0 -not -empty -print | head -n1 | grep -q . && echo 'not empty' || echo 'empty'
find: 'A': No such file or directory
empty
Replace -not -empty
by any other find
expression, but be careful if you -exec
a command that prints to stdout. You may want to grep for a more specific expression in such cases.
This approach works nicely in shell scripts. The originally question was to look for the glob xorg-x11-fonts*
:
if find -maxdepth 0 -name 'xorg-x11-fonts*' -print | head -n1 | grep -q .
then
: the glob matched
else
: ...not
fi
Note that the else-branched is reached if xorg-x11-fonts*
had not matched, or find
encountered an error. To distinguish the case use $?
.
1
You probably meant -maxdepth 1 when using -name, since -maxdepth 0 will look at the current directory and not its contents.
– Chris Cogdon
Jul 29 '16 at 23:40
add a comment |
IMHO it's better to use find
always when testing for files, globs or directories. The stumbling block in doing so is find
's exit status: 0 if all paths were traversed successfully, >0 otherwise. The expression you passed to find
creates no echo in its exit code.
The following example tests if a directory has entries:
$ mkdir A
$ touch A/b
$ find A -maxdepth 0 -not -empty -print | head -n1 | grep -q . && echo 'not empty'
not empty
When A
has no files grep
fails:
$ rm A/b
$ find A -maxdepth 0 -not -empty -print | head -n1 | grep -q . || echo 'empty'
empty
When A
does not exist grep
fails again because find
only prints to stderr:
$ rmdir A
$ find A -maxdepth 0 -not -empty -print | head -n1 | grep -q . && echo 'not empty' || echo 'empty'
find: 'A': No such file or directory
empty
Replace -not -empty
by any other find
expression, but be careful if you -exec
a command that prints to stdout. You may want to grep for a more specific expression in such cases.
This approach works nicely in shell scripts. The originally question was to look for the glob xorg-x11-fonts*
:
if find -maxdepth 0 -name 'xorg-x11-fonts*' -print | head -n1 | grep -q .
then
: the glob matched
else
: ...not
fi
Note that the else-branched is reached if xorg-x11-fonts*
had not matched, or find
encountered an error. To distinguish the case use $?
.
1
You probably meant -maxdepth 1 when using -name, since -maxdepth 0 will look at the current directory and not its contents.
– Chris Cogdon
Jul 29 '16 at 23:40
add a comment |
IMHO it's better to use find
always when testing for files, globs or directories. The stumbling block in doing so is find
's exit status: 0 if all paths were traversed successfully, >0 otherwise. The expression you passed to find
creates no echo in its exit code.
The following example tests if a directory has entries:
$ mkdir A
$ touch A/b
$ find A -maxdepth 0 -not -empty -print | head -n1 | grep -q . && echo 'not empty'
not empty
When A
has no files grep
fails:
$ rm A/b
$ find A -maxdepth 0 -not -empty -print | head -n1 | grep -q . || echo 'empty'
empty
When A
does not exist grep
fails again because find
only prints to stderr:
$ rmdir A
$ find A -maxdepth 0 -not -empty -print | head -n1 | grep -q . && echo 'not empty' || echo 'empty'
find: 'A': No such file or directory
empty
Replace -not -empty
by any other find
expression, but be careful if you -exec
a command that prints to stdout. You may want to grep for a more specific expression in such cases.
This approach works nicely in shell scripts. The originally question was to look for the glob xorg-x11-fonts*
:
if find -maxdepth 0 -name 'xorg-x11-fonts*' -print | head -n1 | grep -q .
then
: the glob matched
else
: ...not
fi
Note that the else-branched is reached if xorg-x11-fonts*
had not matched, or find
encountered an error. To distinguish the case use $?
.
IMHO it's better to use find
always when testing for files, globs or directories. The stumbling block in doing so is find
's exit status: 0 if all paths were traversed successfully, >0 otherwise. The expression you passed to find
creates no echo in its exit code.
The following example tests if a directory has entries:
$ mkdir A
$ touch A/b
$ find A -maxdepth 0 -not -empty -print | head -n1 | grep -q . && echo 'not empty'
not empty
When A
has no files grep
fails:
$ rm A/b
$ find A -maxdepth 0 -not -empty -print | head -n1 | grep -q . || echo 'empty'
empty
When A
does not exist grep
fails again because find
only prints to stderr:
$ rmdir A
$ find A -maxdepth 0 -not -empty -print | head -n1 | grep -q . && echo 'not empty' || echo 'empty'
find: 'A': No such file or directory
empty
Replace -not -empty
by any other find
expression, but be careful if you -exec
a command that prints to stdout. You may want to grep for a more specific expression in such cases.
This approach works nicely in shell scripts. The originally question was to look for the glob xorg-x11-fonts*
:
if find -maxdepth 0 -name 'xorg-x11-fonts*' -print | head -n1 | grep -q .
then
: the glob matched
else
: ...not
fi
Note that the else-branched is reached if xorg-x11-fonts*
had not matched, or find
encountered an error. To distinguish the case use $?
.
edited Mar 20 '16 at 11:37
answered Mar 20 '16 at 10:38
Andreas SpindlerAndreas Spindler
4,50423230
4,50423230
1
You probably meant -maxdepth 1 when using -name, since -maxdepth 0 will look at the current directory and not its contents.
– Chris Cogdon
Jul 29 '16 at 23:40
add a comment |
1
You probably meant -maxdepth 1 when using -name, since -maxdepth 0 will look at the current directory and not its contents.
– Chris Cogdon
Jul 29 '16 at 23:40
1
1
You probably meant -maxdepth 1 when using -name, since -maxdepth 0 will look at the current directory and not its contents.
– Chris Cogdon
Jul 29 '16 at 23:40
You probably meant -maxdepth 1 when using -name, since -maxdepth 0 will look at the current directory and not its contents.
– Chris Cogdon
Jul 29 '16 at 23:40
add a comment |
if [ `ls path1/* path2/* 2> /dev/null | wc -l` -ne 0 ]; then echo ok; else echo no; fi
add a comment |
if [ `ls path1/* path2/* 2> /dev/null | wc -l` -ne 0 ]; then echo ok; else echo no; fi
add a comment |
if [ `ls path1/* path2/* 2> /dev/null | wc -l` -ne 0 ]; then echo ok; else echo no; fi
if [ `ls path1/* path2/* 2> /dev/null | wc -l` -ne 0 ]; then echo ok; else echo no; fi
answered Oct 2 '17 at 3:09
Dan EliasDan Elias
111
111
add a comment |
add a comment |
Try this
fileTarget="xorg-x11-fonts*"
filesFound=$(ls $fileTarget) # 2014-04-03 edit 2: removed dbl-qts around $(...)
edit 2014-04-03 (removed dbl-quotes and added test file 'Charlie 22.html' (2 spaces)
case ${filesFound} in
"" ) printf "NO files found for target=${fileTarget}n" ;;
* ) printf "FileTarget Files found=${filesFound}n" ;;
esac
Test
fileTarget="*.html" # where I have some html docs in the current dir
FileTarget Files found=Baby21.html
baby22.html
charlie 22.html
charlie21.html
charlie22.html
charlie23.html
fileTarget="xorg-x11-fonts*"
NO files found for target=xorg-x11-fonts*
Note that this only works in the current directory, or where the var fileTarget
includes the path you are want to inspect.
Your code will fail iffileTarget
contains whitespace (e.g.,fileTarget="my file*"
).
– Richard Hansen
Jun 17 '11 at 6:34
@RichardHansen what the solution when there is whitespace?
– Ross
Mar 28 '14 at 22:57
@Ross: Use the accepted answer:if ls "my file"* >/dev/null 2>&1; then ...
– Richard Hansen
Mar 29 '14 at 2:59
@RichardHansen thanks, sorry – not working for me. Have it fixed now .
– Ross
Apr 2 '14 at 9:44
1
@Ross, I've added an edit to mine that should work with files with spaces. Basicallycase "${filesFound}" in ....
. Good luck to all.
– shellter
Apr 2 '14 at 11:23
|
show 2 more comments
Try this
fileTarget="xorg-x11-fonts*"
filesFound=$(ls $fileTarget) # 2014-04-03 edit 2: removed dbl-qts around $(...)
edit 2014-04-03 (removed dbl-quotes and added test file 'Charlie 22.html' (2 spaces)
case ${filesFound} in
"" ) printf "NO files found for target=${fileTarget}n" ;;
* ) printf "FileTarget Files found=${filesFound}n" ;;
esac
Test
fileTarget="*.html" # where I have some html docs in the current dir
FileTarget Files found=Baby21.html
baby22.html
charlie 22.html
charlie21.html
charlie22.html
charlie23.html
fileTarget="xorg-x11-fonts*"
NO files found for target=xorg-x11-fonts*
Note that this only works in the current directory, or where the var fileTarget
includes the path you are want to inspect.
Your code will fail iffileTarget
contains whitespace (e.g.,fileTarget="my file*"
).
– Richard Hansen
Jun 17 '11 at 6:34
@RichardHansen what the solution when there is whitespace?
– Ross
Mar 28 '14 at 22:57
@Ross: Use the accepted answer:if ls "my file"* >/dev/null 2>&1; then ...
– Richard Hansen
Mar 29 '14 at 2:59
@RichardHansen thanks, sorry – not working for me. Have it fixed now .
– Ross
Apr 2 '14 at 9:44
1
@Ross, I've added an edit to mine that should work with files with spaces. Basicallycase "${filesFound}" in ....
. Good luck to all.
– shellter
Apr 2 '14 at 11:23
|
show 2 more comments
Try this
fileTarget="xorg-x11-fonts*"
filesFound=$(ls $fileTarget) # 2014-04-03 edit 2: removed dbl-qts around $(...)
edit 2014-04-03 (removed dbl-quotes and added test file 'Charlie 22.html' (2 spaces)
case ${filesFound} in
"" ) printf "NO files found for target=${fileTarget}n" ;;
* ) printf "FileTarget Files found=${filesFound}n" ;;
esac
Test
fileTarget="*.html" # where I have some html docs in the current dir
FileTarget Files found=Baby21.html
baby22.html
charlie 22.html
charlie21.html
charlie22.html
charlie23.html
fileTarget="xorg-x11-fonts*"
NO files found for target=xorg-x11-fonts*
Note that this only works in the current directory, or where the var fileTarget
includes the path you are want to inspect.
Try this
fileTarget="xorg-x11-fonts*"
filesFound=$(ls $fileTarget) # 2014-04-03 edit 2: removed dbl-qts around $(...)
edit 2014-04-03 (removed dbl-quotes and added test file 'Charlie 22.html' (2 spaces)
case ${filesFound} in
"" ) printf "NO files found for target=${fileTarget}n" ;;
* ) printf "FileTarget Files found=${filesFound}n" ;;
esac
Test
fileTarget="*.html" # where I have some html docs in the current dir
FileTarget Files found=Baby21.html
baby22.html
charlie 22.html
charlie21.html
charlie22.html
charlie23.html
fileTarget="xorg-x11-fonts*"
NO files found for target=xorg-x11-fonts*
Note that this only works in the current directory, or where the var fileTarget
includes the path you are want to inspect.
edited Apr 3 '14 at 3:27
answered Jun 15 '11 at 20:16
shelltershellter
29.3k66075
29.3k66075
Your code will fail iffileTarget
contains whitespace (e.g.,fileTarget="my file*"
).
– Richard Hansen
Jun 17 '11 at 6:34
@RichardHansen what the solution when there is whitespace?
– Ross
Mar 28 '14 at 22:57
@Ross: Use the accepted answer:if ls "my file"* >/dev/null 2>&1; then ...
– Richard Hansen
Mar 29 '14 at 2:59
@RichardHansen thanks, sorry – not working for me. Have it fixed now .
– Ross
Apr 2 '14 at 9:44
1
@Ross, I've added an edit to mine that should work with files with spaces. Basicallycase "${filesFound}" in ....
. Good luck to all.
– shellter
Apr 2 '14 at 11:23
|
show 2 more comments
Your code will fail iffileTarget
contains whitespace (e.g.,fileTarget="my file*"
).
– Richard Hansen
Jun 17 '11 at 6:34
@RichardHansen what the solution when there is whitespace?
– Ross
Mar 28 '14 at 22:57
@Ross: Use the accepted answer:if ls "my file"* >/dev/null 2>&1; then ...
– Richard Hansen
Mar 29 '14 at 2:59
@RichardHansen thanks, sorry – not working for me. Have it fixed now .
– Ross
Apr 2 '14 at 9:44
1
@Ross, I've added an edit to mine that should work with files with spaces. Basicallycase "${filesFound}" in ....
. Good luck to all.
– shellter
Apr 2 '14 at 11:23
Your code will fail if
fileTarget
contains whitespace (e.g., fileTarget="my file*"
).– Richard Hansen
Jun 17 '11 at 6:34
Your code will fail if
fileTarget
contains whitespace (e.g., fileTarget="my file*"
).– Richard Hansen
Jun 17 '11 at 6:34
@RichardHansen what the solution when there is whitespace?
– Ross
Mar 28 '14 at 22:57
@RichardHansen what the solution when there is whitespace?
– Ross
Mar 28 '14 at 22:57
@Ross: Use the accepted answer:
if ls "my file"* >/dev/null 2>&1; then ...
– Richard Hansen
Mar 29 '14 at 2:59
@Ross: Use the accepted answer:
if ls "my file"* >/dev/null 2>&1; then ...
– Richard Hansen
Mar 29 '14 at 2:59
@RichardHansen thanks, sorry – not working for me. Have it fixed now .
– Ross
Apr 2 '14 at 9:44
@RichardHansen thanks, sorry – not working for me. Have it fixed now .
– Ross
Apr 2 '14 at 9:44
1
1
@Ross, I've added an edit to mine that should work with files with spaces. Basically
case "${filesFound}" in ....
. Good luck to all.– shellter
Apr 2 '14 at 11:23
@Ross, I've added an edit to mine that should work with files with spaces. Basically
case "${filesFound}" in ....
. Good luck to all.– shellter
Apr 2 '14 at 11:23
|
show 2 more comments
How about
if ls -l | grep -q 'xorg-x11-fonts.*' # grep needs a regex, not a shell glob
then
# do something
else
# do something else
fi
1
No, don't usels
in scripts and the.*
wildcard is redundant (you probably meantgrep -q '^xorg-x1-fonts'
).
– tripleee
Sep 26 '17 at 9:08
why not parsels
– phuclv
May 31 '18 at 8:48
add a comment |
How about
if ls -l | grep -q 'xorg-x11-fonts.*' # grep needs a regex, not a shell glob
then
# do something
else
# do something else
fi
1
No, don't usels
in scripts and the.*
wildcard is redundant (you probably meantgrep -q '^xorg-x1-fonts'
).
– tripleee
Sep 26 '17 at 9:08
why not parsels
– phuclv
May 31 '18 at 8:48
add a comment |
How about
if ls -l | grep -q 'xorg-x11-fonts.*' # grep needs a regex, not a shell glob
then
# do something
else
# do something else
fi
How about
if ls -l | grep -q 'xorg-x11-fonts.*' # grep needs a regex, not a shell glob
then
# do something
else
# do something else
fi
answered Jun 23 '17 at 2:08
abcabc
8,8292489147
8,8292489147
1
No, don't usels
in scripts and the.*
wildcard is redundant (you probably meantgrep -q '^xorg-x1-fonts'
).
– tripleee
Sep 26 '17 at 9:08
why not parsels
– phuclv
May 31 '18 at 8:48
add a comment |
1
No, don't usels
in scripts and the.*
wildcard is redundant (you probably meantgrep -q '^xorg-x1-fonts'
).
– tripleee
Sep 26 '17 at 9:08
why not parsels
– phuclv
May 31 '18 at 8:48
1
1
No, don't use
ls
in scripts and the .*
wildcard is redundant (you probably meant grep -q '^xorg-x1-fonts'
).– tripleee
Sep 26 '17 at 9:08
No, don't use
ls
in scripts and the .*
wildcard is redundant (you probably meant grep -q '^xorg-x1-fonts'
).– tripleee
Sep 26 '17 at 9:08
why not parse
ls
– phuclv
May 31 '18 at 8:48
why not parse
ls
– phuclv
May 31 '18 at 8:48
add a comment |
If there is a huge amount of files on a network folder using the wildcard is questionable (speed, or command line arguments overflow).
I ended up with:
if [ -n "$(find somedir/that_may_not_exist_yet -maxdepth 1 -name *.ext -print -quit)" ] ; then
echo Such file exists
fi
add a comment |
If there is a huge amount of files on a network folder using the wildcard is questionable (speed, or command line arguments overflow).
I ended up with:
if [ -n "$(find somedir/that_may_not_exist_yet -maxdepth 1 -name *.ext -print -quit)" ] ; then
echo Such file exists
fi
add a comment |
If there is a huge amount of files on a network folder using the wildcard is questionable (speed, or command line arguments overflow).
I ended up with:
if [ -n "$(find somedir/that_may_not_exist_yet -maxdepth 1 -name *.ext -print -quit)" ] ; then
echo Such file exists
fi
If there is a huge amount of files on a network folder using the wildcard is questionable (speed, or command line arguments overflow).
I ended up with:
if [ -n "$(find somedir/that_may_not_exist_yet -maxdepth 1 -name *.ext -print -quit)" ] ; then
echo Such file exists
fi
edited Sep 2 '17 at 8:00
answered Sep 2 '17 at 7:49
luxigoluxigo
9015
9015
add a comment |
add a comment |
You can also cut other files out
if [ -e $( echo $1 | cut -d" " -f1 ) ] ; then
...
fi
this would be slow because of the subshell. And what if the file name contains space?
– phuclv
May 31 '18 at 8:49
add a comment |
You can also cut other files out
if [ -e $( echo $1 | cut -d" " -f1 ) ] ; then
...
fi
this would be slow because of the subshell. And what if the file name contains space?
– phuclv
May 31 '18 at 8:49
add a comment |
You can also cut other files out
if [ -e $( echo $1 | cut -d" " -f1 ) ] ; then
...
fi
You can also cut other files out
if [ -e $( echo $1 | cut -d" " -f1 ) ] ; then
...
fi
edited Oct 10 '17 at 20:43
JakeGould
20.8k85076
20.8k85076
answered Oct 2 '17 at 14:25
McCloudMcCloud
12
12
this would be slow because of the subshell. And what if the file name contains space?
– phuclv
May 31 '18 at 8:49
add a comment |
this would be slow because of the subshell. And what if the file name contains space?
– phuclv
May 31 '18 at 8:49
this would be slow because of the subshell. And what if the file name contains space?
– phuclv
May 31 '18 at 8:49
this would be slow because of the subshell. And what if the file name contains space?
– phuclv
May 31 '18 at 8:49
add a comment |
Using new fancy shmancy features in ksh, bash, and zsh shells (this example doesn't handle spaces in filenames):
# Declare a regular array (-A will declare an associative array. Kewl!)
declare -a myarray=( /mydir/tmp*.txt )
array_length=${#myarray[@]}
# Not found if the 1st element of the array is the unexpanded string
# (ie, if it contains a "*")
if [[ ${myarray[0]} =~ [*] ]] ; then
echo "No files not found"
elif [ $array_length -eq 1 ] ; then
echo "File was found"
else
echo "Files were found"
fi
for myfile in ${myarray[@]}
do
echo "$myfile"
done
Yes, this does smell like Perl. Glad I didn't step in it ;)
add a comment |
Using new fancy shmancy features in ksh, bash, and zsh shells (this example doesn't handle spaces in filenames):
# Declare a regular array (-A will declare an associative array. Kewl!)
declare -a myarray=( /mydir/tmp*.txt )
array_length=${#myarray[@]}
# Not found if the 1st element of the array is the unexpanded string
# (ie, if it contains a "*")
if [[ ${myarray[0]} =~ [*] ]] ; then
echo "No files not found"
elif [ $array_length -eq 1 ] ; then
echo "File was found"
else
echo "Files were found"
fi
for myfile in ${myarray[@]}
do
echo "$myfile"
done
Yes, this does smell like Perl. Glad I didn't step in it ;)
add a comment |
Using new fancy shmancy features in ksh, bash, and zsh shells (this example doesn't handle spaces in filenames):
# Declare a regular array (-A will declare an associative array. Kewl!)
declare -a myarray=( /mydir/tmp*.txt )
array_length=${#myarray[@]}
# Not found if the 1st element of the array is the unexpanded string
# (ie, if it contains a "*")
if [[ ${myarray[0]} =~ [*] ]] ; then
echo "No files not found"
elif [ $array_length -eq 1 ] ; then
echo "File was found"
else
echo "Files were found"
fi
for myfile in ${myarray[@]}
do
echo "$myfile"
done
Yes, this does smell like Perl. Glad I didn't step in it ;)
Using new fancy shmancy features in ksh, bash, and zsh shells (this example doesn't handle spaces in filenames):
# Declare a regular array (-A will declare an associative array. Kewl!)
declare -a myarray=( /mydir/tmp*.txt )
array_length=${#myarray[@]}
# Not found if the 1st element of the array is the unexpanded string
# (ie, if it contains a "*")
if [[ ${myarray[0]} =~ [*] ]] ; then
echo "No files not found"
elif [ $array_length -eq 1 ] ; then
echo "File was found"
else
echo "Files were found"
fi
for myfile in ${myarray[@]}
do
echo "$myfile"
done
Yes, this does smell like Perl. Glad I didn't step in it ;)
answered Feb 22 '18 at 16:12
Ben SladeBen Slade
1148
1148
add a comment |
add a comment |
Found a couple of neat solutions worth sharing. The first still suffers from "this will break if there's too many matches" problem:
pat="yourpattern*" matches=($pat) ; [[ "$matches" != "$pat" ]] && echo "found"
(Recall that if you use an array without the [ ]
syntax, you get the first element of the array.)
If you have "shopt -s nullglob" in your script, you could simply do:
matches=(yourpattern*) ; [[ "$matches" ]] && echo "found"
Now, if it's possible to have a ton of files in a directory, you're pretty well much stuck with using find:
find /path/to/dir -maxdepth 1 -type f -name 'yourpattern*' | grep -q '.' && echo 'found'
add a comment |
Found a couple of neat solutions worth sharing. The first still suffers from "this will break if there's too many matches" problem:
pat="yourpattern*" matches=($pat) ; [[ "$matches" != "$pat" ]] && echo "found"
(Recall that if you use an array without the [ ]
syntax, you get the first element of the array.)
If you have "shopt -s nullglob" in your script, you could simply do:
matches=(yourpattern*) ; [[ "$matches" ]] && echo "found"
Now, if it's possible to have a ton of files in a directory, you're pretty well much stuck with using find:
find /path/to/dir -maxdepth 1 -type f -name 'yourpattern*' | grep -q '.' && echo 'found'
add a comment |
Found a couple of neat solutions worth sharing. The first still suffers from "this will break if there's too many matches" problem:
pat="yourpattern*" matches=($pat) ; [[ "$matches" != "$pat" ]] && echo "found"
(Recall that if you use an array without the [ ]
syntax, you get the first element of the array.)
If you have "shopt -s nullglob" in your script, you could simply do:
matches=(yourpattern*) ; [[ "$matches" ]] && echo "found"
Now, if it's possible to have a ton of files in a directory, you're pretty well much stuck with using find:
find /path/to/dir -maxdepth 1 -type f -name 'yourpattern*' | grep -q '.' && echo 'found'
Found a couple of neat solutions worth sharing. The first still suffers from "this will break if there's too many matches" problem:
pat="yourpattern*" matches=($pat) ; [[ "$matches" != "$pat" ]] && echo "found"
(Recall that if you use an array without the [ ]
syntax, you get the first element of the array.)
If you have "shopt -s nullglob" in your script, you could simply do:
matches=(yourpattern*) ; [[ "$matches" ]] && echo "found"
Now, if it's possible to have a ton of files in a directory, you're pretty well much stuck with using find:
find /path/to/dir -maxdepth 1 -type f -name 'yourpattern*' | grep -q '.' && echo 'found'
answered Mar 9 '18 at 21:43
Chris CogdonChris Cogdon
3,35222426
3,35222426
add a comment |
add a comment |
man test
if [ -e file ]; then
...
fi
will work for dirfile.
regards
9
This will not work with wildcards (which is what is asked in this question). If it matches more than one file you will getbash: [: too many arguments
– user000001
Apr 17 '13 at 13:28
1
A little unfair as this works very well on Solaris........
– SnazzyBootMan
Oct 9 '15 at 14:47
heh, old post, thanks for the support Chris - i was indeed working with Solaris back then as well.
– Shokodemon
Sep 24 '17 at 13:09
add a comment |
man test
if [ -e file ]; then
...
fi
will work for dirfile.
regards
9
This will not work with wildcards (which is what is asked in this question). If it matches more than one file you will getbash: [: too many arguments
– user000001
Apr 17 '13 at 13:28
1
A little unfair as this works very well on Solaris........
– SnazzyBootMan
Oct 9 '15 at 14:47
heh, old post, thanks for the support Chris - i was indeed working with Solaris back then as well.
– Shokodemon
Sep 24 '17 at 13:09
add a comment |
man test
if [ -e file ]; then
...
fi
will work for dirfile.
regards
man test
if [ -e file ]; then
...
fi
will work for dirfile.
regards
answered Apr 16 '13 at 22:02
ShokodemonShokodemon
93
93
9
This will not work with wildcards (which is what is asked in this question). If it matches more than one file you will getbash: [: too many arguments
– user000001
Apr 17 '13 at 13:28
1
A little unfair as this works very well on Solaris........
– SnazzyBootMan
Oct 9 '15 at 14:47
heh, old post, thanks for the support Chris - i was indeed working with Solaris back then as well.
– Shokodemon
Sep 24 '17 at 13:09
add a comment |
9
This will not work with wildcards (which is what is asked in this question). If it matches more than one file you will getbash: [: too many arguments
– user000001
Apr 17 '13 at 13:28
1
A little unfair as this works very well on Solaris........
– SnazzyBootMan
Oct 9 '15 at 14:47
heh, old post, thanks for the support Chris - i was indeed working with Solaris back then as well.
– Shokodemon
Sep 24 '17 at 13:09
9
9
This will not work with wildcards (which is what is asked in this question). If it matches more than one file you will get
bash: [: too many arguments
– user000001
Apr 17 '13 at 13:28
This will not work with wildcards (which is what is asked in this question). If it matches more than one file you will get
bash: [: too many arguments
– user000001
Apr 17 '13 at 13:28
1
1
A little unfair as this works very well on Solaris........
– SnazzyBootMan
Oct 9 '15 at 14:47
A little unfair as this works very well on Solaris........
– SnazzyBootMan
Oct 9 '15 at 14:47
heh, old post, thanks for the support Chris - i was indeed working with Solaris back then as well.
– Shokodemon
Sep 24 '17 at 13:09
heh, old post, thanks for the support Chris - i was indeed working with Solaris back then as well.
– Shokodemon
Sep 24 '17 at 13:09
add a comment |
17
Two bugs with your code: (1) The asterisk has to be outside the double quotes (a quoted asterisk loses it special wildcard meaning), and (2) if multiple files match the pattern, multiple arguments will be passed to the
[
command, most likely causing[
to exit with an error and therefore be interpreted as no files matching.– Richard Hansen
Jun 17 '11 at 6:31