Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
16
rated 0 times [  16] [ 0]  / answers: 1 / hits: 16752  / 1 Year ago, sun, december 11, 2022, 12:47:12

I want to know the difference between aliases and functions in the bash shell - and when to use which one.



It seems obvious that since functions can take arguments, they are a lot more powerful - since I work mainly on the road with a netbook and want to save energy and processing power, I would especially like to know a little more about what the performance differences of this two ways to extend bash functionality are.


More From » bash

 Answers
7

Think of aliases as nicknames. You might have a command that you perform a lot but want to shorten.



As an example, you often want to go straight to desktop in commandline, so you can do this



alias desktop="cd ~/Desktop"


From then on you just type



desktop


in terminal and it will perform the cd ~/Desktop for you.



Functions contains logic. In a function, you might make calls to several different programs. Here's a simple echo function



function e {
echo $1
echo $1 $1
echo $1 $1 $1
}


While it may appear similar to an alias when you call it



e Hello


Your e() can have a lot of different things happen. The above is a simplistic example.



Aliases should be reserved for simple use cases. Personal example - I have replaced my rm command like this



alias rm='trash-put'


Whenever I do an rm, it will send it to trash instead of deleting it from disk. This caters to my clumsiness in the terminal where I may (sometimes) accidentally delete an important file.



Functions, you need to remember, are pieces of logic. You wouldn't use a function standalone, usually. It would be part of a larger script. Imagine a script which takes all of your files and renames them to their pig latin versions. Ignore that there are different ways of doing it.



But what you could do is loop through every file in the directory and pass the filepath to your RenameAsPigLatin function. The RenameAsPigLatin function might have extra logic in there involving numbers, where you decide that files ending with numbers shouldn't be renamed.



Immediately you can see the benefit of having it as a function. The function can focus on the renaming by your strange rules while the rest of the script can traverse various directories as necessary.


[#36838] Sunday, December 11, 2022, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
fertion

Total Points: 436
Total Questions: 121
Total Answers: 156

Location: England
Member since Sun, May 21, 2023
1 Year ago
fertion questions
Thu, Mar 9, 23, 06:46, 1 Year ago
Thu, Jun 17, 21, 01:06, 3 Years ago
Mon, Jun 13, 22, 07:30, 2 Years ago
Fri, Mar 10, 23, 12:13, 1 Year ago
;