Bash – How to save a function in bash for later use

bashfunction

I have this function to get MAC address from IP:

ip2arp()  {
   local ip="$1"
   ping -c1 -w1 "$ip" >/dev/null
   arp -n "$ip" | awk '$1==ip {print $3}' ip="$ip"
   }

What is the right way for using it later? Save to /usr/bin as sh and make it executable, or save it in a home directory and make an alias in bash? Is there a right and wrong way?

Best Answer

If it's only for your personal use then you could add it to your shell's initialization file as a function, e.g. ~/.bashrc.

For a summary of the different initialization files in Bash you can consult the Bash Guide for Beginners:

Also see the Bash Reference Manual:

A typical pattern would be to put your function definition in your ~/.bashrc file and source that file from your ~/.bash_profile.

But it's probably worth noting that which profile file to use can depend on your OS, your terminal application, and your own preferences. See for example the following posts on AskDifferent:

Also see this post on StackOverflow:

Alternatively, you can create a personal directory for your own scripts (e.g. I use ~/local/bin) and then add that directory to your PATH in your profile file (i.e. export PATH="${HOME}/local/bin:${PATH}).

If you want to make it available to other users then you might put it in /usr/local/bin as a script (rather than /usr/bin).

For further discussion regarding where to put executable files, see the following posts:

Related Question