Is it possible to do the following:
I want to run the following:
mongodb bin/mongod
In my bash_profile I have
alias = "./path/to/mongodb/$1"
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.
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. Place variables in quotes if the values might have spaces in them.
To make the alias persistent you need to declare it in the ~/. bash_profile or ~/. bashrc file. The aliases should be named in a way that is easy to remember.
Sometimes we need to create an alias that accepts parameters. Since the alias command created in Bash does not accept parameters directly, we’ll have to create a Bash function. The syntax of the Bash function is: <function_name> { <commands> }
Aliases don't take arguments. With an alias like alias foo='bar $1', the $1 will be expanded by the shell to the shell's first argument (which is likely nothing) when the alias is run. So: Use functions, instead. num=$ {1:-5} uses the first argument, with a default value of 5 if it isn't provided.
For bash script, I can use "$@" to access arguments. What's the equivalent when I use an alias? Show activity on this post. If you're really against using a function per se, you can use: You can replace $@ with $1 if you only want the first argument. This creates a temporary function f, which is passed the arguments.
The second one (the bar alias) has several side effects. Firstly the command can't use stdin. Secondly, if no arguments are provided after the alias, whatever arguments the shell happens to have gets passed instead. Using a function avoids all these side effects. (Also useless use of cat).
An alias will expand to the string it represents. Anything after the alias will appear after its expansion without needing to be or able to be passed as explicit arguments (e.g. $1
).
$ alias foo='/path/to/bar' $ foo some args
will get expanded to
$ /path/to/bar some args
If you want to use explicit arguments, you'll need to use a function
$ foo () { /path/to/bar "$@" fixed args; } $ foo abc 123
will be executed as if you had done
$ /path/to/bar abc 123 fixed args
To undefine an alias:
unalias foo
To undefine a function:
unset -f foo
To see the type and definition (for each defined alias, keyword, function, builtin or executable file):
type -a foo
Or type only (for the highest precedence occurrence):
type -t foo
Usually when I want to pass arguments to an alias in Bash, I use a combination of an alias and a function like this, for instance:
function __t2d { if [ "$1x" != 'x' ]; then date -d "@$1" fi } alias t2d='__t2d'
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