I am learning Linux commands and I learnt that you can write a shell script and put in a customized directory (e.g. ~/bin/
) and export to $PATH
or you can write it as a shell function and put in .bashrc
file.
If I may ask, what is the right situation or reason to use either? which one is more recommended?
Thank you!
when you want something that modifies your shell environment (e.g. your ENV variables, your prompt etc..), it is better to make it a function that stays in your .bashrc. Typically, one of the functions I often use, is one that changes my environment for working with /usr/local
or /opt
etc.. updating the $PATH
, $LD_PATH
, $PYTHON_PATH
orders.
When you make a whole program that takes advantage of shell scripting, then it is better in its own file, in a bin/ directory. Typically, you want to automatize a task, filter output using a complex piping of seds and awks (e.g. count the number of different IPs appear in the ssh logs?) that makes a good use case of a script.
Functions work better as small, self-contained blocks. Scripts work better for longer, more complex tasks (which could be composed of smaller functions itself). Keep in mind that a script stored in ~/bin
will be launched in a separate processes (unless you take the effort to run it as source myScript
instead).
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