Home > Blockchain >  Use argument in bash command in first part of a pipe
Use argument in bash command in first part of a pipe

Time:01-18

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?

CodePudding user response:

*.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'
  • Related