Linux Shell Script: list contents of a directory into a file
i have to write a shell script that gets a directory name as a parameter and then lists the names and sizes of the files in the directory into a text file. I have little knowledge of linux so can you please help me? All i managed to write is this:
for entry in "$search_dir"/* do if [ -f "$entry" ];then echo "$entry" fi done
filename1 filesize1 filename2 filesize2
4 Answers 4
You could easily put the output of a script into a file using >
will dump the ls command into the contentsOfDir.txt in your current directory.
The script could look like this for a bash shell:
#!/bin/bash ls -l $1 > contentsOfDir.txt
./myScript dirNameToBeDumpedInFile
Have a look at this bash scripting tutorial, it covers the basics.
If you want to print a pretty tree of the folder content and it’s subfolders, you can use «tree».
If it’s not install on your system, You need to do so first:
Then the syntax is pretty simple. If you want to save the output to a file:
tree -h -A path/to/dir > output.txt
- -A is used to make sure the output is using ASCII characters.
- -h will print each file size in a human readable format.
You have more options to limit the output that you can get by using the «—help» option:
> tree --help -a All files are listed. -d List directories only. -l Follow symbolic links like directories. -f Print the full path prefix for each file. -L level Descend only level directories deep. -o filename Output to file instead of stdout. -s Print the size in bytes of each file. -h Print the size in a more human readable way. --dirsfirst List directories before files (-U disables).
How can I export a recursive directory & file listing to a text file in Linux Bash shell with an SSH command?
Assume I’m in my pwd — /home/kparisi/ What command can I run to export all directories & files from this directory and all subdirectories within it to a text file? I don’t need the contents of the files, just their names & paths (and permissions if possible) Thanks in advance.
This is probably more appropriate on superuser — See e.g. superuser.com/a/200684 . You can redirect into a file by appending > myfile.txt to the end of the command line
4 Answers 4
Use find to get a listing of all the files in a directory and its subdirectories, then pipe it to a file with the > operand.
find is a good utility to obtain (recursively) all the content of a directory. If you want the file (and directory) names with their permissions:
find /home/kparisi -printf "%M %p\n"
You can then use ssh to run this command on the remote server:
ssh kparisi@remote.com 'find /home/kparisi -printf "%M %p\n"'
And finally, if you want to store this in a file on your local server:
ssh kparisi@remote.com 'find /home/kparisi -printf "%M %p\n"' > file
I understand that it is an old question, but anyway if somebody will reach this page, maybe will be useful. I love to do this (assume we have the file «fsstruct.txt» to save directory structure):
for me this format is simpler to read.
It is easy also to use other features of tree:
prints file type and permissions before file and it is more accessible when you are reading plain text, which is a file and which is a directory.
this: tree -ph > fsstruct.txt prints sizes of files in a human readable format.
Also, it is possible to send output to the file: tree -ph . -o fsstruct.txt or create HTML: tree -Hph . -o tree.html
Get a list of all files in folder and sub-folder in a file
How do I get a list of all files in a folder, including all the files within all the subfolders and put the output in a file?
7 Answers 7
You can do this on command line, using the -R switch (recursive) and then piping the output to a file thus:
this will make a file called filename1 in the current directory, containing a full directory listing of the current directory and all of the sub-directories under it.
You can list directories other than the current one by specifying the full path eg:
will list everything in and under /var and put the results in a file in the current directory called filename2. This works on directories owned by another user including root as long as you have read access for the directories.
You can also list directories you don’t have access to such as /root with the use of the sudo command. eg:
sudo ls -R /root > filename3
Would list everything in /root, putting the results in a file called filename3 in the current directory. Since most Ubuntu systems have nothing in this directory filename3 will not contain anything, but it would work if it did.
Maybe telling the person to cd into the directory first could be added to answer.Also this works fine if i own the directory but if trying in a directory say owned by root it didnt.I got the usual permission denied and sudo followed by your command also gave permission denied. IS there a work around without logging in as root?
Well I did say «current» directory. The correct use of CD might the subject of another question, and I’m sure it has been. You can list directories owned by root as long as you have read access to them. Directories owned by root to which the user has read access can be listed with ls -R. It’s hard to imagine why you’d want to list directories owned by root to which you don’t have read access, but sudo does indeed work if you give the full path. I’m adding examples for both of these, but excluding the use of CD.
Just use the find command with the directory name. For example to see the files and all files within folders in your home directory, use
Also check find GNU info page by using info find command in a terminal.
This is the most powerful approach. find has many parameters to customize output format and file selection.
That’s the best approach in my opinion. Simple and practical. Could also do $ find . > output if there’s many directories.
tree
An alternative to recursive ls is the command line tool tree that comes with quite a lot of options to customize the format of the output diplayed. See the manpage for tree for all options.
will give you the same as tree using other characters for the lines.
to display hidden files too
- Go to the folder you want to get a content list from.
- Select the files you want in your list ( Ctrl + A if you want the entire folder).
- Copy the content with Ctrl + C .
- Open gedit and paste the content using Ctrl + V . It will be pasted as a list and you can then save the file.
This method will not include subfolder, content though.
You could also use the GUI counterpart to Takkat’s tree suggestion which is Baobab. It is used to view folders and subfolders, often for the purpose of analysing disk usage. You may have it installed already if you are using a GNOME desktop (it is often called disk usage analyser).
sudo apt-get install baobab
You can select a folder and also view all its subfolders, while also getting the sizes of the folders and their contents as the screenshot below shows. You just click the small down arrow to view a subfolder within a folder. It is very useful for gaining a quick insight into what you’ve got in your folders and can produce viewable lists, but at the present moment it cannot export them to file. It has been requested as a feature, however, at Launchpad. You can even use it to view the root filesystem if you use gksudo baobab .
(You can also get a list of files with their sizes by using ls -shR ~/myfolder and then export that to file.)
Справочная информация
Возникла необходимость экспортировать содержимое каталога в файл, другими словами – создать листинг содержания каталога.
Найти «по-быстрому» ответ на этот, вроде бы простой вопрос, оказалось затруднительно. Нет, команда вывода содержания каталога была отображена на многих ресурсах, но это касалось вывода в окно терминала. А далее следовали отсылки к документации на команду ls. Пробую набрать ls —help и чувствую, что потихоньку «зверею».
Вернуть душевное равновесие помог «звонок другу». Оказывается, команда должна быть: ls расположение_каталога>file.txt
Осталось проверить это на практике, то есть вывести содержание одного из каталогов с музыкой mp3 в текстовый файл.
Каталог /home/cemea/Clouds/Алёна Апина/Ритмические
Копирую в буфер обмена этот путь:
/home/cemea/Clouds/Алёна Апина/Ритмические
Запускаю терминал и ввожу команду ls, затем через пробел из буфера обмена вставляю скопированный путь и после ввожу >AR.txt, где AR.txt будет являться файлом, в котором будет перечислено содержание каталога.
Так как в указании пути к каталогу имеется пробел, то весь путь должен быть помещён в одинарные или двойные кавычки. Поэтому полная терминальная команда будет иметь вид:
ls ‘/home/cemea/Clouds/Алёна Апина/Ритмические’>AR.txt
ls «/home/cemea/Clouds/Алёна Апина/Ритмические»>AR.txt
В результате в домашнем каталоге наблюдаю появление файла AR.txt, при открытии которого наблюдается его содержание:
01. Электричка.mp3
02. Было, девки, было.mp3
03. Объяснение в любви.mp3
04. Пароходик.mp3
05. Нелюбимый.mp3
06. Тополя.mp3
07. Непрошенный ангел.mp3
08. А я любила тебя.mp3
09. Пляжный сезон.mp3
10. Ну когда под венец.mp3
11. Подари мне цветы.mp3
12. Разноцветные сны.mp3
13. Эх, хоть бы раз. mp3
14. Поезда.mp3
15. Я погадаю.mp3
16. На теплоходе музыка играет.mp3
17. Сенсация.mp3
Не закрывая текстового редактора, через верхнее меню вызываю команду «Поиск – Заменить». В нижней части в строке «Найти» ввожу .mp3, а в строке «Заменить на:» не ввожу ничего, либо символ пробела. Далее нажимаю кнопку «Заменить всё».
В итоге получаю красивый список:
01. Электричка
02. Было, девки, было
03. Объяснение в любви
04. Пароходик
05. Нелюбимый
06. Тополя
07. Непрошенный ангел
08. А я любила тебя
09. Пляжный сезон
10. Ну когда под венец
11. Подари мне цветы
12. Разноцветные сны
13. Эх, хоть бы раз.
14. Поезда
15. Я погадаю
16. На теплоходе музыка играет
17. Сенсация