100 Useful Command-Line Utilities

by Oliver; 2014

4. ls

ls lists the files and directories in the cwd, if we leave off arguments. If we pass directories to the command as arguments, it will list their contents. Here are some common flags.

Display our files in a column:
$ ls -1  # list vertically with one line per item
List in long form—show file permissions, the owner of the file, the group to which he belongs, the date the file was created, and the file size:
$ ls -l  # long form
List in human-readable (bytes will be rounded to kilobytes, gigabytes, etc.) long form:
$ ls -hl  # long form, human readable
List in human-readable long form sorted by the time the file was last modified:
$ ls -hlt # long form, human readable, sorted by time
List in long form all files in the directory, including dotfiles:
$ ls -al  # list all, including dot- files and dirs
Since you very frequently want to use ls with these flags, it makes sense to alias them:
alias ls="ls --color=auto"
alias l="ls -hl --color=auto"
alias lt="ls -hltr --color=auto"
alias ll="ls -al --color=auto"
The coloring is key. It will color directories and files and executables differently, allowing you to quickly scan the contents of your folder.

Note that you can use an arbitrary number of arguments and that bash uses the convention that an asterik matches anything. For example, to list only files with the .txt extension:
$ ls *.txt 
This is known as globbing. What would the following do?
$ ls . dir1 .. dir2/*.txt dir3/A*.html
This monstrosity would list anything in the cwd; anything in directory dir1; anything in the directory one above us; anything in directory dir2 that ends with .txt; and anything in directory dir3 that starts with A and ends with .html. You get the point!

ls can be useful in for-loops:
$ for i in $( ls /some/path/*.txt ); do echo $i; done
With this construct, we could do some series of commands on all .txt files in /some/path. You can also do a very similar thing without ls:
$ for i in /some/path/*.txt; do echo $i; done

<PREV   NEXT>