3

My question is very similar to that of this old post.

I would like to do something similar: place in an alias the last argument(s) typed on the current command line. This would be equivalent to the csh \!* which can be used in aliases.

According to the referenced post, it sounds as though the issue is the history expansion of bash, which is why fc is used instead. The idea would be to have the substitution work in the middle of a string of commands, such as alias cat='cat -n !!:* && echo ""' (as a simplified example, which doesn't work because of the expansion issue).

However, this differs from the referenced post in the sense that I want to grab only the arguments beyond the first command (i.e. in the post, they grab the entire line, rather than the entire line except for the zero-th argument, the command itself).

What is the best way to do this in a bash alias? (Note: looking to keep this as an alias, not looking for a script or function).

1
  • There's a big difference between a script and a function. A bash function lives in memory, just like an alias; there's no reason not to use one here. Using history substitutions in csh aliases to do more than simple replacement of the command is a hack that is only needed because csh doesn't have proper subroutines.
    – Mark Reed
    Nov 20, 2012 at 12:59

1 Answer 1

2

It is best to avoid aliases for anything other than simple, one-command substitutions. To use arguments, multiple commands, etc., you can define a function, accessing parameters the same way you would in a script:

foo() {
    do_this
    do_that "$1"
}

cat() { command cat "$@" && echo ""; }

(Normally functions override executables, so command cat is needed if you want to skip the function and directly run the executable.)

2
  • Thanks, but I added the edit "(Note: looking to keep this as an alias, not looking for a script or function)." Aliases can be a powerful tool, and--even if only for academic reasons--I would prefer to see what it takes to get this equivalent functionality (e.g. compared to other shells, such as csh). On a separate token, perhaps this just is ultimately more a difference of the mindset of bash versus other shell paradigms?
    – bossNova
    Feb 23, 2012 at 19:17
  • Aliases were never intended to support arguments in the middle of an alias; they have always been just a simple command substitution. Using history expansion within an alias has always been a horrible hack, and these days is mostly used in shells which do not support anything better -- and bash does have a better option; namely, functions. Feb 23, 2012 at 19:26

You must log in to answer this question.

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