256

The other answers provide some soft general guidelines based on personal taste, but ignore many pertinent facts that one should consider when deciding between scripts, functions, or aliases. Aliases and Functions ¹ The entire contents of aliases and functions are stored in the shell's memory. A natural consequence of this is aliases and functions can ...


239

An alias should effectively not (in general) do more than change the default options of a command. It is nothing more than simple text replacement on the command name. It can't do anything with arguments but pass them to the command it actually runs. So if you simply need to add an argument at the front of a single command, an alias will work. Common ...


197

The shell command and any arguments to that command appear as numbered shell variables: $0 has the string value of the command itself, something like script, ./script, /home/user/bin/script or whatever. Any arguments appear as "$1", "$2", "$3" and so on. The count of arguments is in the shell variable "$#". Common ways of dealing with this involve shell ...


163

You can access passed arguments with $n where n is the argument number - 1, 2, 3, .... You pass the arguments just like you would with any other command. $ cat myscript #!/bin/bash echo "First arg: $1" echo "Second arg: $2" $ ./myscript hello world First arg: hello Second arg: world


115

In Bash you can export function definitions to sub-shell with export -f function_name For example you can try this simple example: ./script1: #!/bin/bash myfun() { echo "Hello!" } export -f myfun ./script2 ./script2: #!/bin/bash myfun Then if you call ./script1 you will see the output Hello!.


88

The function keyword was introduced in ksh. The traditional Bourne shell only had the foo () syntax, and POSIX standardizes only the foo () syntax. In ATT ksh (but not pdksh), there are a few differences between functions defined by function and functions defined with the Bourne/POSIX syntax. In functions defined by function, the typeset keyword declares a ...


72

The number passed to the _exit()/exit_group() system call (sometimes referred as the exit code to avoid the ambiguity with exit status which is also referring to an encoding of either the exit code or signal number and additional info depending on whether the process was killed or exited normally) is of type int, so on Unix-like systems like Linux, typically ...


65

Readability is one thing. But there is more to modularisation than just this. (Semi-modularisation is maybe more correct for functions.) In functions you can keep some variables local, which increases reliability, decreasing the chance of things getting messed up. Another pro of functions is re-usability. Once a function is coded, it can be applied ...


64

Sourcing the changed file will provide access to the newly written alias or function in the current terminal, for example: source ~/.bashrc An alternative syntax: . ~/.bashrc Note that if you have many instances of bash running in your terminal (you mentionned multiple tabs), you will have to run this in every instance.


57

Because, according to bash(1), cd takes arguments cd [-L|[-P [-e]] [-@]] [dir] Change the current directory to dir. if dir is not supplied, ... so therefore the directory actually may not be in $1 as that could instead be an option such as -L or another flag. How bad is this? $ cd -L /var/tmp $ pwd /var/tmp $ cd() { builtin cd "...


45

I have a handy bash function called calc: calc () { bc -l <<< "$@" } Example usage: $ calc 65320/670 97.49253731343283582089 $ calc 65320*670 43764400 You can change this to suit yourself. For example: divide() { bc -l <<< "$1/$2" } Note: <<< is a here string which is fed into the stdin of bc. You don't need to ...


44

In typical imperative programming, you write sequences of instructions and they are executed one after the other, with explicit control flow. For example: if [ -f file1 ]; then # If file1 exists ... cp file1 file2 # ... create file2 as a copy of a file1 fi etc. As can be seen from the example, in imperative programming you follow the execution ...


42

There is no difference AFAIK, other than the fact that the second version is more portable.


41

Positional parameters refer to the script's arguments in the main level of the script, but to function arguments in function body. So print_something Something would actually print Something. If you want to pass the script's arguments to a function, you must do that explicitly. Use print_something "$1" to pass the first argument, or print_something "$@"...


39

In my comment, I mentioned three advantages of functions: They are easier to test and verify correctness. Functions can be easily reused (sourced) in future scripts Your boss likes them. And, never underestimate the importance of number 3. I would like to address one more issue: ... so being able to arbitrarily swap the run order isn't something we ...


39

I've started using this same style of bash programming after reading Kfir Lavi's blog post "Defensive Bash Programming". He gives quite a few good reasons, but personally I find these the most important: procedures become descriptive: it's much easier to figure out what a particular part of code is supposed to do. Instead of wall of code, you see "Oh, the ...


36

The Advanced Bash-Scripting Guide is not always reliable and its example scripts contain out-dated practices such as using the effectively deprecated backticks for command substitution, i.e., `command` rather than $(command). In this particular case, it’s blatantly incorrect. The section on Shell Functions in the (canonical) Bash manual definitively states ...


35

I think it's up to each person's taste. For me the logic goes like this: First I try to make an alias, because it's the simplest. If the thing is too complicated to fit in one line, I try to make it a function. When the function starts to grow beyond a dozen of lines I put it in a script. There is really nothing to restrict you from doing something that ...


34

I'm getting 2 from your code. Nevertheless, you can use the same technique for any variable or number: local start=1 (( start++ )) or (( ++start )) or (( start += 1 )) or (( start = start + 1 )) or just local start=1 echo $(( start + 1 )) etc.


32

foo() any-command is the Bourne syntax supported by any Bourne-like shell but bash, yash and recent versions of posh (which only support compound commands). (the Bourne shell and AT&T implementations of ksh don't support foo() any-command > redirections unless any-command is a compound command though). foo() any-compound-command (examples of ...


32

Like others have said, you can't do that. But if you want to arrange the code into one file so that the main program is at the top of the file, and other functions are defined below, you can do it by having a separate main function. E.g. #!/bin/sh main() { if [ "$1" = yes ]; then do_task_this else do_task_that fi } ...


31

Curly brace functions will run within the calling shell process, unless they need their own subshell which is: when you run them in the background with & when you run them as a link in a pipeline Redirections or extra env. variables won't force a new subshell: hw(){ echo hello world from $BASHPID echo var=$var } var=42 hw >&2 echo $...


27

$/shellscriptname.sh argument1 argument2 argument3 You can also pass output of one shell script as an argument to another shell script. $/shellscriptname.sh "$(secondshellscriptname.sh)" Within shell script you can access arguments with numbers like $1 for first argument and $2 for second argument and so on so forth. More on shell arguments


26

Aliases are expanded when a function definition is read, not when the function is executed … $ echo "The quick brown fox jumps over the lazy dog." > myfile   $ alias myalias=cat   $ myfunc() { > myalias myfile > }   $ myfunc The quick brown fox jumps over the lazy dog.   $ alias myalias="ls -l"   $ myalias myfile -rw-r--r-- 1 myusername mygroup ...


25

A function is local to a shell, so you'd need find -exec to spawn a shell and have that function defined in that shell before being able to use it. Something like: find ... -exec ksh -c ' function foo { echo blan: "$@" } foo "$@"' ksh {} + bash allows one to export functions via the environment with export -f, so you can do (in bash): foo() { ......


25

What is happening is that you are recursively calling your ls function. In order to use the binary, you can use ZSH's command builtin. function ls { command ls -l "$@" }


25

First it's important to note that what makes a function a callback function is how it's used, not what it does. A callback is when code that you write is called from code that you didn't write. You're asking the system to call you back when some particular event happens. An example of a callback in shell programming is traps. A trap is a callback that isn't ...


24

From man bash: When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the ...


24

d=$d/.. adds /.. to the current contents of the d variable. d starts off empty, then the first iteration makes it /.., the second /../.. etc. sed 's/^\///' drops the first /, so /../.. becomes ../.. (this can be done using a parameter expansion, d=${d#/}). d=.. only makes sense in the context of its condition: if [ -z "$d" ]; then d=.. fi This ensures ...


22

Semantically, those two forms are equivalent in Bash. From the man page: Shell functions are declared as follows: name () compound-command [redirection] function name [()] compound-command [redirection] This defines a function named name. The reserved word function is optional. If the function reserved word is supplied, the parentheses ...


Only top voted, non community-wiki answers of a minimum length are eligible