Aliases with arguments linux

How to pass command line arguments to a shell alias? [duplicate]

But in this case the $xx is getting translated at the alias creating time and not at runtime. I have, however, created a workaround using a shell function (after googling a little) like below:

Just wanted to know if there is a way to make aliases that accept CL parameters.
BTW — I use ‘bash’ as my default shell.

O/T but about as an alternative to doing a mkcd function, you can write mkdir mydirectoryname && cd $_

11 Answers 11

Just to reiterate what has been posted for other shells, in Bash the following works:

alias blah='function _blah()< echo "First: $1"; echo "Second: $2"; >;_blah' 

Great solution. Some questions from a bash novice: Does the function have to be named with an underscore (or differently at all) or is that just for readability? What is the purpose of the trailing «;_blah» in defining the function? Why does it not work when using double quotes in place of single quotes (the $1 is not interpreted correctly) even when doing something that does not require quotes around the $1? Thanks in advance for the advice. I have a working solution but always like to understand more on why it works.

@mynameispaulie The function can be named anything. I’ve used an an underscore prefix as it is a common trick to help prevent name collisions (ie another function with the same name)

@mynameispaulie The double quotes allow Bash to replace $1 and $2 with the parameters passed to the function. Single quotes tell Bash not to do this.

I see this alias/function combo copy/pasted a lot, but it does not seem to serve any useful purpose. The standard approach would be to define the function once, with a sane name, and not have an alias.

You found the way: create a function instead of an alias. The C shell has a mechanism for doing arguments to aliases, but bash and the Korn shell don’t, because the function mechanism is more flexible and offers the same capability.

You however don’t need functions when creating aliases in .bashrc file. For example # create an alias that takes port-number by the user alias serve=»python -m SimpleHTTPServer $1″ After making the change in the .bashrc file, make sure you enter the following command. ~$ source .bashrc You should be able to use this like so ~$ serve 8998

@kaizer1v, My observation on CentOS7.3 bash version 4.2.46 is that your suggestion doesn’t work as you think it does. Because you are using double quotes the $1 is actually being evaluated to an empty string and the alias is actually the same as alias serve=»python -m SimpleHTTPServer» and so whatever you pass after that alias is ALSO passed on the command line. If you try this set -x; alias serve=»python -m SimpleHTTPServer $1 &» you will see the error/problem. Both your argument and the alias command are run as separate commands.

Читайте также:  Отключение графической оболочки linux

Functions do NOT offer the same capability as aliases. Aliases can be generated inside of a code block and affect surrounding structures (breaking from a while loop, starting a do block but not ending it, etc). I use this mechanism extensively to support elegant exception handling and trace logging in bash that could never be done with functions. Alias needs to be able to take parameters also to fully unlock it’s potential.

Источник

How to Create Bash Alias with Arguments and Parameters

In a BASH environment, we construct an alias for a set of files. Alias can be made more programmatic and versatile by using BASH functions, variables, etc. Bash Alias is a method for creating a few shortcut commands for numerous and repetitive operations. Here, we will discuss a way to create the bash alias with the arguments and parameters. Unfortunately, there are some cases when the alias does not accept parameters or arguments. However, we can utilize functions to accept parameters and arguments while executing alias commands. We use the bash aliases and functions to use the command line more efficiently.

Creating the Bash Alias

We already have some predefined aliases. By giving the alias command without any parameter displayed all the aliases that are already set on our system. We have opened the terminal below and specified it with the following command:

The configured alias in our system is fetched out after running this specific command. Notice that there is an alert alias at the top of the listing. Then, a couple of aliases are available for the grep command family that outputs color information. After that, we have various alias for the “ls” command. If the custom alias is created, it will also appear in the list.

We have configured the alias of our system. Now, we have to create a custom alias which is very simple in Linux. By using the structure provided below, we can define the aliases in the command line.

The alias keyword is used to declare the new alias name. As in the above alias command, we have named the alias “test”. Then, we specified the command to alias observed by the equal to sign. The command to alias here is ‘ls -l’ which lists all the directories and files in our system including the hidden ones.

Bash Alias Accepting the Arguments

We have created the alias “MyTest” with the alias structure. Now, we are going to pass an argument to that alias. By default, an alias can accept the arguments. The below command is passing the argument to the above-created alias “MyTest”. The argument here is the current directory “/”.

After just creating the alias on the terminal, we executed the alias accepting argument command which listed all the directories associated with our alias.

The alias can also accept multiple arguments at a time. Let us have the following command where we have provided the “home” directory and the “root” directory as an argument to the “MyTest” alias.

The output of the above alias accepting multiple arguments displayed the results in the terminal.

Читайте также:  What linux distributions have you used

Bash Alias Accepting the Parameters

Sometimes, we encounter a situation where the alias does not accept more than one argument and parameter. For this purpose, we used the bash functions to accept the various arguments and parameters. Here we are employing a basic bash function that will establish a directory and allow users to enter it without using the mkdir commands.

The “Newmkcd” is the name of the bash function inside which we have passed the parameters “$1” and “$2”. We can insert more arguments according to our choice. It depends on where the parameter is placed after the bash function name. Note that the reserved bash function name will be stored in the $0 variable. The AND operator “&&” is utilized between these parameters to verify that if the first parameter is carried out successfully, only the second parameter is executed. Further, this dash “–” ensures no more parameters are in the function. Now that we have created the bash function, the new directory can easily be made and moved into that directory.

Bash Alias Accepting the Parameters in the .bashrc

Bash shell functions can be defined in the “.bashrc” file, however, it is frequently better to place them in their own definitions file. The. bashrc file is found in the home directory of our system. When an interactive shell is opened, this file is read, and its arguments are carried out. We have to open the terminal and paste the below command.

When the above command is run in the shell, it starts the “.bashrc” file on the system. There, we can see the different alias is already defined. We have to scroll down the file until the following section is reached.

All we have to do is copy that “bash_aliases” section by pressing the Ctrl+C and then paste that copied section into the same “.bashrc” file. Next, we have assigned a new name “bash_MyFunctions” to “bash_aliases” as shown in the following script snap. It then saves these changes and closes the “.bashrc” file.

Further, we created the bash_MyFunction file by using the touch command in the terminal to edit it and add a function definition.

The .bash_MyFunctions file is created here. Now, we have launched it by specifying the following command on the shell.

Inside the file, we have defined the following bash shell function which accepts the arguments and the parameters.

Here, we have begun with the keyword “function” and set the function name “up()”. The function up() accepts just one digit-based command-line parameter. Then, we declared the variable “levels” which is set with the first parameter “$1”. The “$1” serves as the first command line parameter and it indicates a number provided by the user. After that, we deployed the “while” condition which compares the value of the “$levels” is greater than zero or positive. The while loop further contained the “cd..” command to increase the level within the directory tree. Next, is the “levels=$(($levels-1))” command. This expression sets the value of the level that is lesser than the current value.

If the level is “0” or greater than “0”, the loop runs again. And if the “$level” value is not greater than zero and has a negative value then the loop terminates here. We have saved the file and run the command which is provided below.

Читайте также:  Настройка межсетевого экрана astra linux

The “..bashrc” command reads the “bash_MyFunctions” file when executed in the terminal. Now, we have given a specific point in the directory tree and then used up “2” to get back to a “higher” point.

Conclusion

The guide is on how to create a bash alias with the arguments and parameters. We have explored the way which leads us to pass the arguments and parameters to the bash alias. We began with the creation of the bash alias and then run the shortcut command to pass the single and multiple arguments in the alias. After that, we have provided another way which is the bash function to pass the arguments and parameters to the alias. We became familiar with the Bash shell’s syntax for alias creation and recognized scenarios in which we want to parameterize aliases using Bash functions.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.

Источник

Passing argument to alias in bash [duplicate]

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 

If you want to use explicit arguments, you’ll need to use a function

will be executed as if you had done

$ /path/to/bar abc 123 fixed args 

To see the type and definition (for each defined alias, keyword, function, builtin or executable file):

Or type only (for the highest precedence occurrence):

@10basetom: If you’re referring to the colors in my answer, that’s done automatically by the syntax highlighter.

to use parameters in aliases, i use this method:

alias myalias='function __myalias() < echo "Hello $*"; unset -f __myalias; >; __myalias' 

its a self-destructive function wrapped in an alias, so it pretty much is the best of both worlds, and doesnt take up an extra line(s) in your definitions. which i hate, oh yeah and if you need that return value, you’ll have to store it before calling unset, and then return the value using the «return» keyword in that self destructive function there:

alias myalias='function __myalias() < echo "Hello $*"; myresult=$?; unset -f __myalias; return $myresult; >; __myalias' 

you could, if you need to have that variable in there

alias mongodb='function __mongodb() < ./path/to/mongodb/$1; unset -f __mongodb; >; __mongodb' 
alias mongodb='./path/to/mongodb/' 

would actually do the same thing without the need for parameters, but like i said, if you wanted or needed them for some reason (for example, you needed $2 instead of $1), you would need to use a wrapper like that. If it is bigger than one line you might consider just writing a function outright since it would become more of an eyesore as it grew larger. Functions are great since you get all the perks that functions give (see completion, traps, bind, etc for the goodies that functions can provide, in the bash manpage).

I hope that helps you out 🙂

Источник

Оцените статью
Adblock
detector