Search code examples
bashfunctiondefault-valueparameter-expansion

How can I add a default parameter to a `Bash` function?


Most of the time when I am in some directory and running some job from the command line, I like to do:

ls -ltr | tail -3

to confirm that the file I'm expecting is indeed there.

To avoid typing it too often, I add to my ~/.bach_profile:

alias ltr="ls -ltr | tail -3"

Bash doesn't accept parameters, but we can write

ltr() {
    ls -ltr "${1}" | tail -3
}

After (say) something downloaded, this makes it possible to type ltr ~/Downloads.

But I can no longer type just ltr. I must now type ltr ..

How can I add a default parameter to a Bash function?

(I'm in the macOS Terminal, in case it makes a difference.)


Solution

  • You can use default parameter value like this:

    ltr() {
       ls -ltr "${1:-.}" | tail -3
    }
    

    It will use . as argument to ls -ltr if $1 is missing.

    With this you can use like this:

    ltr ~/Documents
    ltr ~/Downloads
    ltr
    

    Please read this about parsing the output of ls