Variables
There are some rules about variable names:
- Variable names may consist of alphanumeric characters (letters and numbers) and underscore characters.
- The first character of a variable name must be either a letter or an underscore.
- Spaces and punctuation symbols are not allowed.
global variables
#!/bin/bashvar1=1var2=2
local variables
function func() {local foofoo=1}
constant variables
FILENAME='~/.bashrc' # Just a common conventiondeclare -r FILENAME='~/.bashrc' # -r: readonlydeclare -i FILENAME='~/.bashrc' # -i: integer
Parameter Expansion
$VARNAME${VARNAME}
dirname='~/dir/'echo "$dirname"filename=${dirname}filename# bad: filename=$dirnamefilename
declare
#!/bin/bashdeclare -r readonlyVardeclare -i integerVardeclare -u upperVardeclare -l lowerVar
Functions
function name {commandsreturn [EXIT_STATUS] # optional, default return 0, menas success}name {return [EXIT_STATUS]}name # call nameecho $? # ? is exit code of name
- Shell function names follow the same rules as variables.
- A function must contain at least one command.
return [EXIT_STATUS]- Terminate the function with exit status of
EXIT_STATUS - When no argument is passed, the exit status defaults to the exit status of the last command executed.
returncommand is optional, and the exit status defaults to the exit status of the last command executed.
- Terminate the function with exit status of
