Get file list linux

ls command in Linux/Unix

ls is a Linux shell command that lists directory contents of files and directories.

ls syntax

ls command options

ls command main options:

option description
ls -a list all files including hidden file starting with ‘.’
ls —color colored list [=always/never/auto]
ls -d list directories — with ‘ */’
ls -F add one char of */=>@| to enteries
ls -i list file’s inode index number
ls -l list with long format — show permissions
ls -la list long format including hidden files
ls -lh list long format with readable file size
ls -ls list with long format with file size
ls -r list in reverse order
ls -R list recursively directory tree
ls -s list file size
ls -S sort by file size
ls -t sort by time & date
ls -X sort by extension name

ls command examples

You can press the tab button to auto complete the file or folder names.

List directory Documents/Books with relative path:

List directory /home/user/Documents/Books with absolute path.

List root directory:

List parent directory:

List user’s home directory (e.g: /home/user):

List with long format:

Show hidden files:

List with long format and show hidden files:

Sort by date/time:

Sort by file size:

List all subdirectories:

Recursive directory tree list:

List only text files with wildcard:

ls redirection to output file:

List directories only:

List files and directories with full path:

ls code generator

Select ls options and press the Generate Code button:

Источник

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

Источник

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.

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.

Источник

How to get the list of files in a directory in a shell script?

I’m trying to get the contents of a directory using shell script.

where $search_dir is a relative path. However, $search_dir contains many files with whitespaces in their names. In that case, this script does not run as expected.

I know I could use for entry in * , but that would only work for my current directory.

I know I can change to that directory, use for entry in * then change back, but my particular situation prevents me from doing that.

I have two relative paths $search_dir and $work_dir , and I have to work on both simultaneously, reading them creating/deleting files in them etc.

So what do I do now?

9 Answers 9

This is a way to do it where the syntax is simpler for me to understand:

./ is the current working directory but could be replaced with any path
*.txt returns anything.txt
You can check what will be listed easily by typing the ls command straight into the terminal.

Basically, you create a variable yourfilenames containing everything the list command returns as a separate element, and then you loop through it. The loop creates a temporary variable eachfile that contains a single element of the variable it’s looping through, in this case a filename. This isn’t necessarily better than the other answers, but I find it intuitive because I’m already familiar with the ls command and the for loop syntax.

Источник

How to list all files in a directory with absolute paths

I need a file (preferably a .list file) which contains the absolute path of every file in a directory.

Example dir1: file1.txt file2.txt file3.txt

How can I accomplish this in linux/mac?

10 Answers 10

You can use find. Assuming that you want only regular files, you can do:

You can adjust the type parameter as appropriate if you want other types of files.

It’s the shell that computes the list of (non-hidden) files in the directory and passes the list to ls . ls just prints that list here, so you could as well do:

Note that it doesn’t include hidden files, includes files of any type (including directories) and if there’s no non-hidden file in the directory, in POSIX/csh/rc shells, you’d get /current/wd/* as output. Also, since the newline character is as valid as any in a file path, if you separate the file paths with newline characters, you won’t be able to use that resulting file to get back to the list of file reliably.

With the zsh shell, you could do instead:

  • -rC1 prints r aw on 1 C olumn.
  • -N , output records are NUL-delimited instead of newline-delimited (lines) as NUL is the only character that can’t be found in a file name.
  • N : expands to nothing if there’s no matching file ( nullglob )
  • D : include hidden files ( dotglob ).
  • -. : include only regular files ( . ) after symlink resolution ( — ).

Then, you’d be able to do something like:

To remove those files for instance.

You could also use the 😛 modifier in the glob qualifiers to get the equivalent of realpath() on the files expanded from the globs (gets a full path exempt of any symlink component):

To see just regular files —

Another way with tree , not mentioned here, it goes recursively and unlike find or ls you don’t have any errors (like: Permission denied , Not a directory ) you also get the absolute path in case you want to feed the files to xargs or other command

the options meaning:

To install tree :

sudo apt install tree on Ubuntu/Debian

sudo yum install tree on CentOS/Fedora

sudo zypper install tree on OpenSUSE

You can just use realpath or readlink this naughty way:

When ls prints to a TTY it formats the file names in columns, but when it’s writing to a file, pipe, or other non-TTY it behaves like ls -1 and prints one file name per line. You can check this by running ls | cat in place of ls . [1]

  • xargs build and execute command lines from standard input.
  • realpath : return the canonicalized absolute pathname
  • readlink : read value of a symbolic link
  • Use realpath — to make it treat everything that follows as parameters instead of options, if files could have » -something «.
  • If some files have spaces you could:

In a past Linux environment, I had a resolve command that would standardize paths, including making a relative path into an absolute path. I can’t find it now, so maybe it was written by someone in that organization.

You can make your own script using functions in the Python or Perl standard libraries (and probably other languages too).

Then, you would solve your problem with:

With this command, you can also do things like this:

Recursive files can be listed by many ways in linus. Here i am sharing one liner script to clear all logs of files(only files) from /var/log/ directory and second check recently which logs file has made an entry.

note: for directory location you can also pass $PWD instead of /var/log.

To list the full path of all commands (apps/programs) accessible to the user. (revised to address most, but not all limitations outlined in the comments)

NOTE
The PATH variable would normally have a colon ( : ) either at the beginning or at the end, but not both. A colon at the beginning or end signifies to search the current directory as well. Standard practice is for it to be at the end so as to never override standard utility programs. The sed substitutions here handle either case.

Explanation.

  • eval
    Frankly, I don’t know why eval is needed here, but it is. Without it, I get.

ls: cannot access ‘./<.,>[[:word:]]‘: No such file or directory
ls: cannot access ‘/home/alpha/bin/<.,>[[:word:]]
‘: No such file or directory
ls: cannot access ‘/usr/local/sbin/<.,>[[:word:]]‘: No such file or directory
ls: cannot access ‘/usr/local/bin/<.,>[[:word:]]
‘: No such file or directory
ls: cannot access ‘/usr/sbin/<.,>[[:word:]]‘: No such file or directory
ls: cannot access ‘/usr/bin/<.,>[[:word:]]
‘: No such file or directory
ls: cannot access ‘/sbin/<.,>[[:word:]]‘: No such file or directory
ls: cannot access ‘/bin/<.,>[[:word:]]
‘: No such file ordirectory

Источник

Читайте также:  Не показывает флешку mac os
Оцените статью