Open all files in directory linux

How to open a folder in linux via terminal? [closed]

Want to improve this question? Add details and clarify the problem by editing this post.

Closed 7 years ago .

How can I open a folder in a dir?

say I change my current directory to: cd /root/dir/

then I list all the files there: ls folder1 folder2 folder3

Now I want to open folder1. If I try the «./» I get: ./folder1 bash: ./folder1: Is a directory

How can I do so without having to type cd again ie: cd $(pdw)/folder1

5 Answers 5

If you want to open the folder via the nautilus file manager, you can move to the wanted directory like you’ve mentioned cd /root/dir/ , check the folders under that path using ls and then if you want to open folder1 type:

./ is used to execute file (Not to open directory).

(In)CLI Method: You can open folder in terminal by cd folder1 or dir folder1 or ls folder1 .

(To)GUI Method: If you want to open with file-manager (ex:nautilus) then type nautilus folder1 (for Ubuntu nautilus is default file-manager)

I have found that simply typing gnome-open «any-oject» opens any folder or file in the default program on Ubuntu. If this happens to be a folder, it uses your default folder-explorer 🙂

zsh shell can do that with the AUTO_CD option.

Just put setopt AUTO_CD in your .zshrc file (start zsh one time first to create the zsh environment files). You can invoke directly zsh at the terminal prompt to start a zsh session or you can change your default shell to be zsh with the chsh command.

Btw this is not a strange feature, crossable directories do have the «execute» attribute so it makes sense to able to execute a directory like any standard commands.

Источник

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:

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.

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

Check the find manual manpage for the find command

Also check find GNU info page by using info find command in a terminal.

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

to not display lines

  1. Go to the folder you want to get a content list from.
  2. Select the files you want in your list ( Ctrl + A if you want the entire folder).
  3. Copy the content with Ctrl + C .
  4. Open gedit and paste the content using Ctrl + V . It will be pasted as a list and you can then save the file.
Читайте также:  Виртуальная машина virtualbox для линукс virtualbox

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).

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

Источник

Execute command on all files in a directory

Could somebody please provide the code to do the following: Assume there is a directory of files, all of which need to be run through a program. The program outputs the results to standard out. I need a script that will go into a directory, execute the command on each file, and concat the output into one big output file.

For instance, to run the command on 1 file:

10 Answers 10

The following bash code will pass $file to command where $file will represent every file in /dir

  • -maxdepth 1 argument prevents find from recursively descending into any subdirectories. (If you want such nested directories to get processed, you can omit this.)
  • -type -f specifies that only plain files will be processed.
  • -exec cmd option <> tells it to run cmd with the specified option for each file found, with the filename substituted for <>
  • \; denotes the end of the command.
  • Finally, the output from all the individual cmd executions is redirected to results.out

However, if you care about the order in which the files are processed, you might be better off writing a loop. I think find processes the files in inode order (though I could be wrong about that), which may not be what you want.

I’m doing this on my raspberry pi from the command line by running:

The accepted/high-voted answers are great, but they are lacking a few nitty-gritty details. This post covers the cases on how to better handle when the shell path-name expansion (glob) fails, when filenames contain embedded newlines/dash symbols and moving the command output re-direction out of the for-loop when writing the results to a file.

When running the shell glob expansion using * there is a possibility for the expansion to fail if there are no files present in the directory and an un-expanded glob string will be passed to the command to be run, which could have undesirable results. The bash shell provides an extended shell option for this using nullglob . So the loop basically becomes as follows inside the directory containing your files

This lets you safely exit the for loop when the expression ./* doesn’t return any files (if the directory is empty)

or in a POSIX compliant way ( nullglob is bash specific)

This lets you go inside the loop when the expression fails for once and the condition [ -f «$file» ] check if the un-expanded string ./* is a valid filename in that directory, which wouldn’t be. So on this condition failure, using continue we resume back to the for loop which won’t run subsequently.

Also note the usage of — just before passing the file name argument. This is needed because as noted previously, the shell filenames can contain dashes anywhere in the filename. Some of the shell commands interpret that and treat them as a command option when the name are not quoted properly and executes the command thinking if the flag is provided.

Читайте также:  Windows powershell ise установить

The — signals the end of command line options in that case which means, the command shouldn’t parse any strings beyond this point as command flags but only as filenames.

Double-quoting the filenames properly solves the cases when the names contain glob characters or white-spaces. But *nix filenames can also contain newlines in them. So we de-limit filenames with the only character that cannot be part of a valid filename — the null byte ( \0 ). Since bash internally uses C style strings in which the null bytes are used to indicate the end of string, it is the right candidate for this.

So using the printf option of shell to delimit files with this NULL byte using the -d option of read command, we can do below

The nullglob and the printf are wrapped around (..) which means they are basically run in a sub-shell (child shell), because to avoid the nullglob option to reflect on the parent shell, once the command exits. The -d » option of read command is not POSIX compliant, so needs a bash shell for this to be done. Using find command this can be done as

For find implementations that don’t support -print0 (other than the GNU and the FreeBSD implementations), this can be emulated using printf

Another important fix is to move the re-direction out of the for-loop to reduce a high number of file I/O. When used inside the loop, the shell has to execute system-calls twice for each iteration of the for-loop, once for opening and once for closing the file descriptor associated with the file. This will become a bottle-neck on your performance for running large iterations. Recommended suggestion would be to move it outside the loop.

Extending the above code with this fixes, you could do

which will basically put the contents of your command for each iteration of your file input to stdout and when the loop ends, open the target file once for writing the contents of the stdout and saving it. The equivalent find version of the same would be

Источник

Recursively list all files in a directory including files in symlink directories

Suppose I have a directory /dir inside which there are 3 symlinks to other directories /dir/dir11 , /dir/dir12 , and /dir/dir13 . I want to list all the files in dir including the ones in dir11 , dir12 and dir13 .

To be more generic, I want to list all files including the ones in the directories which are symlinks. find . , ls -R , etc stop at the symlink without navigating into them to list further.

8 Answers 8

The -L option to ls will accomplish what you want. It dereferences symbolic links.

So your command would be:

You can also accomplish this with

The -follow option directs find to follow symbolic links to directories.

On Mac OS X use

as -follow has been deprecated.

How about tree? tree -l will follow symlinks.

Disclaimer: I wrote this package.

-type f means it will display real files (not symlinks)

-follow means it will follow your directory symlinks

-print will cause it to display the filenames.

If you want a ls type display, you can do the following

From the find manpage:

If you find you want to only follow a few symbolic links (like maybe just the toplevel ones you mentioned), you should look at the -H option, which only follows symlinks that you pass to it on the commandline.

I knew tree was an appropriate, but I didn’t have tree installed. So, I got a pretty close alternate here

properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the subdirectory pointed to by the symbolic link will be searched.

-L dereferences symbolic links. This will also make it impossible to see any symlinks to files, though — they’ll look like the pointed-to file.

in case you would like to print all file contents: find . -type f -exec cat <> +

Not the answer you’re looking for? Browse other questions tagged linux or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Читайте также:  Linux app update что это

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.10.8.40416

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Linux / UNIX List Open Files for Process

H ow do I list all open files for a Linux or UNIX process using command line options? How can I show open files per process under Linux?

Both Linux and Unix-like operating systems come with various utilities to find out open files associated with the process.

Tutorial details
Difficulty level Easy
Root privileges Yes
Requirements None
Est. reading time 3 minutes

UNIX List Open Files For Process

First use the ps command command to get PID of process, enter:
$ ps -aef | grep $ ps -aef | grep httpd
Next pass this PID to pfiles command under Solaris Unix:
$ pfiles
$ pfiles 3533
See pfiles command documentation> for more information or type the following man command:
% man pfiles

FreeBSD list open files per process

On FreeBSD use the fstat command along with the ps command:
# ps aux | grep -i openvpn # filter outputs using the grep command #
# fstat -p
# fstat -p 1219
We can count open files count for openvpn process as follows using the wc command:
# fstat -p 1219 | grep -v ^USER | wc -l
The -p option passed to the fstat to report all files open by the specified process.

FreeBSD pstat command in action

Linux List Open Files For Process

First you need to find out PID of process. Simply use any one of the following command to obtain process id:
# ps aux | grep OR
$ ps -C -o pid=
For example, find out PID of firefox web-browser, enter:
$ ps -C firefox -o pid=
Output:

To list opne files for firefox process, enter:
$ ls -l /proc/7857/fd
Sample output:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

For privileged process use the sudo command and to count open files use the wc command on Linux as follows:
# Get process pid
sudo ps -C Xorg -o pid
sudo ls -l /proc/$/fd
# Say pid is 9497 for Xorg, then
sudo ls -l /proc/9497/fd | wc -l
We can use bash for loop as follows too:

Listing Open Files on Linux

Using lsof to display the processes using the most file handles

The lsof command list open files under all Linux distributions or UNIX-like operating system. Type the following command to list open file for process ID 351:
$ lsof -p 351
In this example display and count all open files for top 10 processes on Linux operating systems or server:
# lsof | awk ‘‘ | sort | uniq -c | sort -r | head
## force numeric sort by passing the ‘-n’ option to the sort ##
# lsof | awk ‘‘ | sort | uniq -c | sort -r -n | head

  • lsof – Run the lsof to display all open files and send output to the awk
  • awk ‘ – Display first field i.e. process name only
  • uniq -c – Omit duplicate lines while prefix lines by the number of occurrences
  • sort -r – Reverse sort
  • head – Display top 10 process along with open files count

Conclusion

Now you know how to find open files per process on Linux, FreeBSD, and Unix-like systems using various command-line options. See how to increase the system-wide/user-wide number of available (open) file handles on Linux for more information.

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Оцените статью