Title: How to exclude the output file from ls output
Tags: io-redirection;ls
Question: Let's say I have these files on desktop:
aaa.jpg
bbb.jpg
I want to list these two jpg's and output them to a .txt file:
#!/bin/bash
cd ~/Desktop
ls -1 &gt; all.txt
With this code the all.txt would have the following:
aaa.jpg
bbb.jpg
all.txt
I just want the two jpg's in all.txt.
Comment: See also: http://unix.stackexchange.com/a/186126/117549


Here is another answer: thanks for the response, but I wanted to list everything, not just the .jpg. I realized there is a simple solution to that which is
ls * &gt; all.txt
instead of
ls &gt; all.txt
Does anyone know why adding the wildcard would prevent the output file to include itself?
Comment for this answer: This is because the star is expanded to the list of all the entries in the current directory by the shell, before the command is issued. You should post this as a new question for details. Note also that your command has a different behaviour. If there are subdirectories in your directory, their content will be listed too.
Comment for this answer: If you have subdirectories and don't want to expand them, you can do `ls -d * > all.txt`

Here is another answer: you can have the ls filter for only .jpg files
ls *.jpg &gt; all.txt

Here is another answer: A more general solution than the one proposed by @ShayneManning:
ls | grep -v '^all.txt$' &gt; all.txt
grep is used to filter lines by content. The option -v inverses the filter. So, all.txt will be excluded from the output of ls. All the other names will be printed to all.txt.
Comment for this answer: @JeffSchaller indeed... fixed!
Comment for this answer: and will also exclude a file named, for example, "almostall.txt"

{'source': 'StackExchangeDataset', 'subset': 'unix.stackexchange.com', 'metadata': {'AnswerCount': 3, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2016:00:01/26/16', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<io-redirection><ls>', 'Title': 'How to exclude the output file from ls output', 'ViewCount': 1032, 'id': 257835, 'user_AboutMe': None, 'user_AccountId': 7715661.0, 'user_DisplayName': 'Gabby', 'user_Reputation': 31.0, 'user_Views': 12.0, 'user_id': 153436.0}}