0

I want to have a simple function or alias in my bashrc that lists files with ls using all my favorite options and pipes the output to more. Here is how it looks like

l() {
    ls -lh --color $1 | more 
} 

However, when I call this function in a terminal with a wildcard argument, like l *.txt, the blob is resolved before it gets passed to my function. The result is, that I only get the first txt file displayed.

I am afraid that using a function is an overkill for what I want. Is there a way to do this without a function, with just a simple alias?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Dronakuul
  • 147
  • 9
  • Why do you only pass the first argument to ls in your function? – jonrsharpe Jan 17 '23 at 20:04
  • 2
    `*.txt` is not the argument; it's a pattern that the shell *expands* to 1 or more arguments. `$1` only contains the first of them. – chepner Jan 17 '23 at 20:04
  • Thank you for the solution, I didn't know that I could just pass all the resolved arguments with `$@`. That did the trick. – Dronakuul Jan 17 '23 at 20:10

1 Answers1

2

*.txt is not the argument; it's a pattern that could expand (depending on your shell settings) to 0 or more separate arguments. Your function only looks at the first of them.

Use "$@" instead of "$1 to pass all arguments to ls.

l () {
    ls -lh --color "$@" | more
}

The alias would suffice if you weren't trying to pipe the output to more, as aliases don't take arguments.

alias l='ls -lh --color'
chepner
  • 497,756
  • 71
  • 530
  • 681
  • nitpicking: Aliases take arguments, but only at the end of the command. If you like overly-complicated solutions `alias l='sh -c "ls -lh --color \"\$@\" | more" sh'` would do the trick too :) – Socowi Jan 17 '23 at 20:18
  • That's not the alias taking an argument; it's just the alias expansion continuing to precede the arguments on the command line just as the alias itself did. – chepner Jan 17 '23 at 20:21
  • Aliases do not take arguments. See [Aliases](https://www.gnu.org/software/bash/manual/html_node/Aliases.html). `There is no mechanism for using arguments in the replacement text, as in csh. If arguments are needed, use a shell function (see Shell Functions).` – tjm3772 Jan 17 '23 at 20:22
  • Serves me right to receive nitpicks right back. Chepner is right regarding terminology: aliases cannot use *real* arguments; although you can hack something together that feels like it. – Socowi Jan 17 '23 at 20:33