2 ms·
Covered in various parts of responses: Aliases: Use where a simple textual expansion of command arguments, but no other input parsing, is required. Typical e
by dredmorbius 7y ago
Covered in various parts of responses:
Aliases: Use where a simple textual expansion of command arguments, but no other input parsing, is required. Typical examples are to create an "ll" alias for "ls -l":
alias ll='ls -l'
You can shorten commands or supply arguments. If you're doing the latter, you can also look at commands' ENVIRONMENT options, e.g., for less(1), the $LESS environment variable can carry arguments such as "-X", which avoids clearing the terminal on exit (one I employ).
Renaming commands is another common hack, e.g., "alias vi=vim" or "alias awk=gawk" if you want to use a specific variant of a tool or utility. In many cases, your distro's alternatives feature is a better place for this, though individual users on a multi-user system may need to use aliases or other mechanisms. (/etc/aliases is a Debian feature.)
Scripts: These can be of any length, invoke multiple other utilities, run in a separate shell, create their own environment, run as a child of the invoking shell, and exist in their own independent executable file(s). They don't occupy shell memory, and support complex logic incluing if/then, while/do, case, and other branching logic.
Functions: are largely equivalent to scripts, but with some key differences:
- Functions run in the executing shell. Which means functions can change the shell environment, either as an intended or unintended side effect. If you want to change environment variables or the current working directory ($PWD) of the invoking shell, you must use a bash function. Similarly: a command sequence which changes the environment or current working directory, if run as a function, may unexpectedly or unintentionally change the invoking shell's (that is, its own) context.
Scripts and functions are not mutually exclusive. Defining, referencing, and/or using functions within scripts is an excellent way to 1) modularise scripts and 2) achieve results such as changing the environment within the script.
Generally:
- For simple text substitutions, I use aliases.
- Short or simple commands involving arguments and/or branching logic, or specifically intended to change environment, I'll use a function.
- For long-running, complex, batch/cron, or commands in which I don't want the invoking environment to change, I'll use a shell script. That script will often include defined functions.