0

I want to list and sort by time, all the files matching a certain pattern and then get only the first 20:

ls -laths *.txt | head -20

This works well, for example if I create two files:

touch 1.txt
touch 2.txt

The result of the above command is:

$ ls -laths *.txt | head -20
1,5K -rw-rw---- 1 user user 0 20. Apr 09:49 2.txt
1,5K -rw-rw---- 1 user user 0 20. Apr 09:49 1.txt

This works well if I do it on the terminal. But when trying to save it as an alias (where the input $1 is the pattern I want), like this:

alias lis20='function _(){ ls -laths "${1}" | head -20; }; _'

Then when I use the alias, I get:

$ lis20 *.txt
1,5K -rw-rw---- 1 user user 0 20. Apr 09:49 1.txt

It means it only lists the first file. I have tried several expansions of the variable inside, as in this question, but without any success.

I am using zsh, but it would be nice to have a solution that works for both bash and zsh.

0

1 Answer 1

2

Aliases are text expansion, so with lis20 *.txt the alias is first expanded to

function _(){ ls -laths "${1}" | head -20; }; _ *.txt

and then filename generation turns the function call into

_ abc.txt def.txt etc.txt

so in the function, $1 contains only the first matching filename.

Now, you could fix that by using "$@" instead of "$1" in the function instead... ("$@" is magic: despite the quotes, it expands into multiple words, all the arguments separately and intact.)

But then, you don't really need a function and an alias anyway. Just make it a single function:

lis20() {
    ls -laths "$@" | head -20
}
2
  • thanks a lot, that was a very helpful reply. For some reason, I didn't know I can define functions and use them on their own in my .bashrc. I always had them associated with an alias.
    – Santiago
    Commented Apr 20, 2022 at 15:53
  • 1
    @Santiago, .bashrc is just a script, you can do basically anything there that you could do with the shell elsewhere. Including e.g. starting ssh-agent. Just avoid printing output, some automatic tools (like scp) can break with that.
    – ilkkachu
    Commented Apr 20, 2022 at 19:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .