开发者

Pass wildcard to alias

开发者 https://www.devze.com 2023-02-26 19:38 出处:网络
I use a modifies list command as alias (in KSH): alias ltf=\'ls -lrt -d -1 $PWD/*\' So the command ltf displays something like this:

I use a modifies list command as alias (in KSH):

alias ltf='ls -lrt -d -1 $PWD/*'

So the command ltf displays something like this:

-rw-r--r-- 1 myuser mygroup 0 Apr 18 12:00 /us开发者_JS百科r/test.txt

-rw-r--r-- 1 myuser mygroup 0 Apr 18 12:00 /usr/test.log

Now I want to use wildcards. But using ltf *.log does not work.

What is the best way to achieve that?


Update: I want to specify my question because the answers does not solve my problem so far: the command ls -lrt -d -1 $PWD/* executes a list command with some options AND it displays the full path, which is an important point for me.

Unfortunately the alias approach does not allow wildcard parameters. My goal is to make this possible. Probably it is the best way to create the command as a function. This is mentioned in the answers, but it does not work yet (see comments).

Any ideas?


Use a shell function instead of an alias:

function ltf {
  if [ -z "$1" ]; then
    ls -lrtd1 ${PWD}/*
  else
    ls -lrtd1 $1
  fi
}


Your problem is that the wildcards are getting expanded by the shell in your current directory, not in $PWD. You can solve this by using a shell function rather than an alias and doing some quoting (I use $HOME in the example for my convenience) - put this in .bashrc:

ltf() {
    ls $HOME/$*
}

and then:

$ ltf '*.log'


try

alias ltf='ls -lrt -d -1 $1'

or if you want many params

alias ltf='ls -lrt -d -1 $@'


As mentioned by others, wildcard expansion is done before calling shell functions, but not so with an alias.

If you don't need to change the input (which the OP does), this would work fine:

alias ltf='ls -lrt -d -1'

To achieve what the OP wants, within a shell function you would need to use the $@ operator to access the set of files resulting from the wildcard expansion, which you would then need to prepend:

ltf() 
{ 
    #Prepend $PWD to the start of every input
    set -- "${@/#/$PWD/}"   

    #Run the command on the prepended input
    ls -lrt -d -1 $@;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号