Linux - NewbieThis Linux forum is for members that are new to Linux.
Just starting out and have a question?
If it is not in the man pages or the how-to's this is the place!
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Saratha:
Excuse me, I don't mean to hijack your thread, but I wonder if Chris can elaborate on the use of "==" for testing here?
It appears by Saratha's snippet that (in essence) IF "$num" is equal to exactly "0" ; then do_work; else go_home; fi
What's the benefit of say
Code:
if [[ -n $num ]] ; then do_work; else go_home; fi
? Would that work?
so, from some cursory peeking at man bash it appears that
Code:
-n string
True if the length of string is non-zero.
string of "0" vs empty ("")space?
num=$(ls -l|wc -l) here in an empty directory produces
1
so
Code:
[[ $num == 0 ]]
will never happen?
I guess the question to ask is are we testing for empty "$num" using "num=$(ls -l|wc -l)"?
because
(ls -l|wc -l) gives us 1
(ls *|wc -l) gives us 0
Am I confused? Definitely.
I don't understand when one should use
Code:
[[ $variable == 0 ]] or [[ -n $variable ]]
and I'll probably go "oh snap!" 5 seconds after posting this
It would appear we are forgetting the option of having hidden files / directories. Your standard ls will not show hidden items and so the directory may indeed not be empty.
Maybe this old question can help with some alternatives:
If I understand you (Habitual) correctly, the point of not using -n is because even in an empty dir, wc returns '0' which has length(!) eg
Code:
# tmpx is an empty dir ...
cd tmpx
v1=$(ls|wc -l)
if [[ -n $v1 ]]
then
echo "v1 $v1 has len"
fi
# output is
v1 0 has len
Chris: I just want to know an example of when to use "== 0" or when to use '"-n "$VARIABLE"' and how to test for an empty directory.
You didn't quote your variable, how come?
Code:
if [[ -n "$v1" ]]
The output with or without quotes is identical, I just thought it is 'good form' to always quote your(?) variables and use them in upper case.
I also only know that the OP's code snippet begged me to ask "What are you trying to do there?"
I am an odd duck and I don't really have anything to contribute to this discussion except inquiries into my own ignorance.
and I love to code.
OP:
The condition ls -l | wc -l will never return a 0, even for empty directory, it will return 1, so the if [[ $var == 0 ]] condition will never execute.
Code:
~$ mkdir foo
~$ cd foo
~$ ls -l
total 0
~$ ls -l | wc -l
1
You should try like:
Code:
var=$(ls -l | grep -v 'total' | wc -l)
if [[ $var == 0 ]]; then
commands
fi
Last edited by shivaa; 04-05-2013 at 10:53 AM.
Reason: Added 'then' :)
OP:
The condition ls -l | wc -l will never return a 0
That is exactly the answer I was looking for!
So, if "ls -l | wc -l will never return a 0" then it doesn't matter little what operator is...
but if one knows it will never return 0, then it could be programmatically taken care of.
I am a sick puppy as I find these rudimentary topics on logic intriguing and discussing these techniques inspires me.
I have no idea what the OP intended.
- Thanks Gurus!
Last edited by Habitual; 04-08-2013 at 08:49 AM.
Reason: past tense of 'take care'
Re quotes round tested vars; really it depends on how well you know your 'data'. Obviously the most general rule is to use quotes (in case of spaces & other 'odd' chars), but I don't bother unless I know or think I'm going to need to.
It just makes the code 'noisy'.
I'm old school *nix (about 15 yrs usage or so) and never use spaces in filenames etc. OTOH, if you're not the data producer, you may not get a choice eg MS files via Samba.
I'm sure david_the_h would insist on quotes all the time
This leads into the concept of writing shorter/faster code for data processing if you can reasonably rely on the type of values and their range. It may enable you to use shortcuts, rather than always having to use a general soln which will take more (&/or more complex) code, be harder to maintain & take longer to run for instance.
Its really a judgement call
PS Of course you also need good error handling ...
well it's worth nothing that you'd only need quotes if you're using [ / test. Using [[ wouldn't need them as it tokenizes the variables within bash. Does of course make it bash specific though, so it's not as portable.
Yes, I would recommend quotes pretty much all the time. Not just because of word-splitting, but because any globbing characters are interpreted too. You could conceivably end up with a list of filenames instead of the string you expected.
The only time I'd feel safe leaving them off is if you know what you're doing and are certain that there's no chance of surprises. Variables that only contain digits, like counters, are generally safe. But even then it never hurts to keep in the habit and use them anyway.
As for the OP topic, parsing ls like this is not generally recommended. Although to be fair the only real danger comes from the rare chance of a name containing a newline. So I wouldn't argue against it for a quick&dirty count, for a real script you should probably use something more robust.
Assuming a single directory with no recursion, a simple loop is all that's required.
Code:
shopt -s dotglob
for fname in *; do
[[ -f $fname ]] && (( count++ ))
done
echo "$count"
In more advanced cases you may want to load the matching files into an array. That would let you grab the first/last file, for example.
(As you can see, the topic is currently split among two pages.)
Edit: I almost forgot about first setting dotglob, to catch the hidden files.
Also, in bash or ksh, you should use ((..)) to evaluate numerical test conditions, instead of the square bracket tests. Use [[..]] for string and file comparisons.
Code:
if (( count == 0 )); then
Last edited by David the H.; 04-09-2013 at 05:00 PM.
Reason: as stated
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.