I have a bunch of scripts in directory that exists on the path, so I can access each wherever I am. Sometime those are very simple util scripts that "vims" the file. From time to time I would like to quickly see the content of script file and see path to file the script opens (then make cat, grep ...).
I would like to make an alias which will "cat" given script wherever I am.
Given one is not working:
alias a="cat `which \$1`"
If I place script name instead of parameter number($1) it works fine. But
with parameter not.
The second question (I wish life be so so beautiful!) would be getting
auto-completion of script name for that alias.
Using a script that could exist in my "bin" directory would another approach which I can take.
Bash users need to understand that alias cannot take arguments and parameters. But we can use functions to take arguments and parameters while using alias commands.
You can replace $@ with $1 if you only want the first argument. This creates a temporary function f , which is passed the arguments. Alias arguments are only passed at the end. Note that f is called at the very end of the alias.
bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc.
If your function is called "foo" then your completion function could look like this:
If you have the Bash completion package installed:
_foo () { local cur; cur=$(_get_cword); COMPREPLY=( $( compgen -c -- $cur ) ); return 0; }
If you don't:
_foo () { local cur; cur=${COMP_WORDS[$COMP_CWORD]}; COMPREPLY=( $( compgen -c -- $cur ) ); return 0; }
Then to enable it:
complete -F _foo foo
The command compgen -c
will cause the completions to include all commands on your system.
Your function "foo" could look like this:
foo () { cat $(type -P "$@"; }
which would cat
one or more files whose names are passed as arguments.
For the alias with argument, use function instead of aliases :
a() { cat `which $1` ;}
Or if you do it on more than one line, skip th semicolon :
a() {
cat `which $1`
}
You can enter it interactively at the shell prompt :
shell:>a() {
>cat `which $1`
>}
shell:>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With