ls, or listing, command will list all of the ‘visible’ files in a directory by default e.g.
[22:29] centos:~:$ ls setup.sh test_dir workspace
-l flag will provide a long vertical listing similar to a typical GUI file explorer, showing the user and group the files belong to, the permissions for each, size and last updated time:
[22:31] centos:~:$ ls -l total 4 -rwxrwxr-x. 1 centos centos 604 May 5 17:05 setup.sh drwxrwsr-x. 2 centos root 32 Apr 29 11:23 test_dir drwxrwxr-x. 5 centos centos 52 May 13 22:18 workspace
Quick tip: Use the
--human-readable flag for ‘human readable’ file sizes i.e. convert them into KB/MB/GB/etc. rather than bytes.
Earlier I mentioned that by default the
ls command will only list ‘visible’ files. On Linux any file beginning with a dot (.) will be hidden from this listing. By appending the
-a flag it will list all of the dot files too.
[22:33] centos:~:$ ls -a . .. .bash_history .bash_logout .bash_profile .bashrc .gitconfig .pki setup.sh .ssh test_dir .tmux .vim .viminfo .vimrc .weechat workspace
There’s a whole raft of arguments available to the
ls command, all of which can be found on the
man page. Here are a few that I’ve found helpful.
--group-directories-first flag: This flag will group all directories in the listing first, and then list the files, notice the difference between these two:
[22:29] centos:~:$ ls -l --group-directories-first total 4 drwxrwsr-x. 2 centos root 32 Apr 29 11:23 test_dir drwxrwxr-x. 5 centos centos 52 May 13 22:18 workspace -rwxrwxr-x. 1 centos centos 604 May 5 17:05 setup.sh [22:29] centos:~:$ ls -l total 4 -rwxrwxr-x. 1 centos centos 604 May 5 17:05 setup.sh drwxrwsr-x. 2 centos root 32 Apr 29 11:23 test_dir drwxrwxr-x. 5 centos centos 52 May 13 22:18 workspace
Creating aliases: Aliases can be really useful for defaulting some of the above arguments if you use them regularly. A number of Linux distributions will provide some default aliases using
[22:22] centos:~:$ alias alias l.='ls -d .* --color=auto' alias ll='ls -l --color=auto' alias ls='ls --color=auto'
It’s easy to set your own, running the following will set a temporary alias, add it to your .bashrc file to make it permanent:
alias lsd='ls --group-directories-first --color=auto -lah'
lsd into the command line will execute the above
ls command with the listed parameters
There’s a number of other arguments, too minor for their own little section, but could definitely be helpful if you want to use
ls in your shell scripts. For example the
-Q flag will quote all of the entries, which can help with files/directories with spaces in; various sorting flags (sort by modified time, created time, name etc.); different display methods (horizontally [default], long list, single column, comma separated etc.), and many more. Dig into the
man pages to find out more!
Overall a simple command, so an easy introduction to begin with.
Quick tip: You can view the basic specification of my setup in this post here.