1

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.)

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Sam
  • 563
  • 5
  • 15

2 Answers2

1

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

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    Re: parsing the output of ls: IIUC, this applies only if I had inherited someone else's files or file system. In that case I'd need to guard against errors in the output, blundering commands, or downright trojans. But if I'm the one who added every file (with no unusual characters) aside from system files, then I'm considerably safer (with the exception of github-downloaded files etc). Is that about right? – Sam Jun 27 '21 at 20:20
  • @Sam Yes in that case you should be fine – anubhava Jun 28 '21 at 03:07
1

It's not exactly what you're asking for, but in this case it might be better to use this:

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

The "$@" expands to all of the arguments passed to ltr, so you can pass several arguments... or none at all, and whatever you pass gets passed on to ls -ltr.

Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151
  • I think I see where you're going. It might be handy to devise it such that the command mingles the output of two or more directories, and reverse-sorts by timestamp, then passes the output to tail. – Sam Jun 27 '21 at 20:03
  • @Sam Right. Or you can pass additional flags to `ls`, for example `ltr -ia /path/to/dir` would include invisible files and inode numbers while listing /path/to/dir. – Gordon Davisson Jun 27 '21 at 20:07