Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put shell script/function? .bashrc or bin? [closed]

Tags:

linux

bash

shell

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!

like image 876
Mike Lee Avatar asked Sep 11 '25 11:09

Mike Lee


2 Answers

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.

like image 81
zmo Avatar answered Sep 13 '25 02:09

zmo


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).

like image 45
chepner Avatar answered Sep 13 '25 01:09

chepner