What I want is to be able to define custom flags for bash commands/aliases. For example, I have:

alias ll='ls -Alh'
alias la='ls -A'
alias l='ls -lh'

However, I want to set up a custom flag, such as -d, which will also execute ls -d */ on whenever I run the above commands, as such ll -f which would list only hidden directories in a detailed list.

  • aliases don't support spaces and so the best you could do would be to alias "ll-f" as oppsed to "ll -f" – Raman Sailopal Aug 10 '17 at 12:56
  • Use a function instead. Much more capable than simple aliases. – glenn jackman Aug 10 '17 at 14:39

I'm not quite sure what you want with your last sentence, sorry ;)

I'm assuming you want ll to have the functionality of ls -Alh except when it is called by ll -f - in that case it should only list hidden directories. If that's not what you were looking for, it should be relatively easy to adjust. Just add all your flags that have special meaning to the getopts command, and then write a case for each of those flags. The default case should always be break, so that if you pass a flag that doesn't have a special meaning for your function, then ls -Alh gets executed.

In any case, here's a script you can source to define a function called ll (aliases are not powerful to do what you want). You must source, i.e. source <script> the script, so the function gets defined. Be careful to do unalias ll before sourcing the script or unexpected things might happen.

#!/usr/bin/env bash
ll() {
    while getopts ":f" opt; do
        case $opt in
                command ls -Ald .*/
                return 0
    command ls -Alh "$@"

This will cause ll -f to behave as ls -Ald .*/ which lists all hidden directories. If you give ll a flag that is not -f it will default to call ls -Alh "$@" ($@ simply stands for "all arguments"). For example, if you write ll -d Desktop, ls -Alhd Desktop will get executed. If no flags are passed to ll, it will just execute ls -Alh "$@".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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