You can use variables in bash as in any programming language. There are no data types so a variable can contain a number, or a string of characters. There is no need to declare a variable, just assign a value:
STR="Hello World"
echo "$STR"
The VALUE of a variable is retrieved by placing a '$' before the variable name.
When you reference a variable in bash it is important not to put spaces around the equals sign: STR= 2, STR = 2, and STR =2 all mean slightly different things - the extra spaces will not throw a syntax error.
Bash variables may contain the characters: A-Z a-z 0-9 _ they are typically all-caps but lower or mixed case is also supported.
Shell variables are Global within bash, while an environment variable is visible to every process on the OS.
When reading a variable it is often useful to use parameter expansion to clearly indicate the variable name.
For example if you have a variable $MYVAR containing a filename (as a string) and want to do a rename, you might try:mv "$MYVAR" "$MYVAR_bak" # this won't work because bash will expect a variable called MYVAR_bak
To fix this, replace $MYVAR with ${MYVAR} which expands to the string value we want.
mv "$MYVAR" "${MYVAR}_bak"
Example - using the $? shell parameter to obtain an exit code from ls.
#!/bin/bash ls ~/file-that-doesnt-exist EXITCODE=$? if [ "$EXITCODE" = "0" ]; then echo All OK else echo File Not found fi
The shell maintains a list of variables, each of which has as value a list of zero or more words.
The values of shell variables can be displayed and changed with the echo, set and unset commands.
The system maintains its own list of 'environment' variables. These can be displayed and changed with printenv, setenv and unsetenv.
(+) Variables may be made read-only with set -r (q.v.)Read-only variables may not be modified or unset; attempting to do so will cause an error. Once made read-only, a variable cannot be made writable, so set -r should be used with caution. Environment variables cannot be made read-only.
Some variables are set by the shell or referred to by it. For instance, the argv variable is an image of the shell's argument list, and words of this variable's value are referred to in special ways. Some of the variables referred to by the shell are toggles; the shell does not care what their value is, only whether they are set or not.
For instance, the verbose variable is a toggle which causes command input to be echoed. The -v command line option sets this variable. Special shell variables lists all variables which are referred to by the shell.
Bash automatically assigns default values to a number of variables, which are listed below.
Bash uses certain shell variables in the same way as the Bourne shell.
In some cases, Bash assigns a default value to the variable.
CDPATH
- A colon-separated list of directories used as a search path for the
cd
builtin command.HOME
- The current user's home directory; the default for the
cd
builtin command. The value of this variable is also used by tilde expansion.IFS
- A list of characters that separate fields; used when the shell splits words as part of expansion.
- If this parameter is set to a filename and the
MAILPATH
variable is not set, Bash informs the user of the arrival of mail in the specified file.MAILPATH
- A colon-separated list of filenames which the shell periodically checks for new mail. Each list entry can specify the message that is printed when new mail arrives in the mail file by separating the file name from the message with a '?'. When used in the text of the message,
$_
expands to the name of the current mail file.OPTARG
- The value of the last option argument processed by the
getopts
builtin.OPTIND
- The index of the last option argument processed by the
getopts
builtin.PATH
- A colon-separated list of directories in which the shell looks for commands.
PS1
- The primary prompt string. The default value is '\s-\v\$ '.
PS2
- The secondary prompt string. The default value is '> '.
These variables are set or used by Bash, but other shells do not normally treat them specially.
A few variables used by Bash are described in different chapters: variables for controlling the job control facilities.
BASH
BASH_ENV
BASH_VERSION
BASH_VERSINFO
BASH_VERSINFO[0]
BASH_VERSINFO[1]
BASH_VERSINFO[2]
BASH_VERSINFO[3]
BASH_VERSINFO[4]
BASH_VERSINFO[5]
MACHTYPE
. COMP_WORDS
COMP_CWORD
${COMP_WORDS}
of the word containing the current cursor position. This variable is available only in shell functions invoked
by the programmable completion facilities.
COMP_LINE
COMP_POINT
${#COMP_LINE}
.
This variable is available only in shell functions and external commands invoked by the programmable completion facilities.
COMPREPLY
DIRSTACK
dirs
builtin. Assigning to members of this array variable can be used to modify directories already in the stack, but the pushd
and popd
builtins must be used to add and remove directories. Assignment to this variable will not change the current directory. If DIRSTACK
is unset,
it loses its special properties, even if it is subsequently reset.
EUID
FCEDIT
fc
builtin command.
FIGNORE
FIGNORE
is excluded from the list of matched file names. A sample value is '.o:~'
GLOBIGNORE
GLOBIGNORE
, it is removed from the list of matches.
GROUPS
GROUPS
have no effect and are silently discarded. If GROUPS
is unset, it loses its special properties, even if it is subsequently reset.
histchars
HISTCMD
HISTCMD
is unset, it loses its special properties, even if it is subsequently reset.
FUNCNAME
FUNCNAME
have no effect and are silently discarded. If FUNCNAME
is unset, it loses its special properties, even if it is subsequently reset.
HISTCONTROL
HISTCONTROL
.
HISTIGNORE
HISTCONTROL
are applied. In addition to the normal shell pattern matching characters, '&' matches the previous history line.
'&' can be escaped using a backslash; the backslash is removed before attempting a match. The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTIGNORE
. HISTIGNORE
subsumes the function of HISTCONTROL
. A pattern of '&' is
identical to ignoredups
, and a pattern of '[ ]*'
is identical to ignorespace
. Combining these two patterns, separating them with a colon, provides the functionality of ignoreboth
.
HISTFILE
HISTSIZE
HISTFILESIZE
HOSTFILE
HOSTFILE
is set, but has no value, Bash attempts to read /etc/hosts to obtain the list of possible hostname completions. When HOSTFILE
is unset, the hostname list is cleared.
HOSTNAME
HOSTTYPE
IGNOREEOF
EOF
character as the sole input. If set, the value denotes the number of consecutive EOF
characters that can be read as the first character on an input line before the shell will exit. If the variable exists but does not have a numeric value (or has no value) then the default is 10. If the variable does not exist, then EOF
signifies the end of input to the shell. This is only in effect for interactive shells.
INPUTRC
LANG
LC_
.
LC_ALL
LANG
and any other LC_
variable specifying a locale category.
LC_COLLATE
LC_CTYPE
LC_MESSAGES
LC_NUMERIC
LINENO
MACHTYPE
MAILCHECK
MAILPATH
or MAIL
variables.
OLDPWD
cd
builtin.
OPTERR
getopts
builtin command.
OSTYPE
PIPESTATUS
PPID
PROMPT_COMMAND
$PS1
).
PS3
select
command. If this variable is not set, the select
command prompts with '#? '
PS4
PS4
is
replicated multiple times, as necessary, to indicate multiple levels of indirection.
The default is '+ '.
PWD
cd
builtin.
RANDOM
REPLY
read
builtin.
SECONDS
SHELLOPTS
set
builtin command. The options appearing in SHELLOPTS
are those reported as 'on' by 'set -o'. If this variable is
in the environment when Bash starts up, each shell option in the list will be enabled before reading any startup files. This variable is readonly.
SHLVL
TIMEFORMAT
time
reserved
word should be displayed. The '%' character introduces an escape sequence that is expanded to a time value or other information. The escape
sequences and their meanings are as follows; the braces denote optional portions.
%%
%[p][l]R
%[p][l]U
%[p][l]S
%P
l
specifies a longer format, including minutes, of the form MMmSS.FFs. The value of p determines whether or not the fraction is included. If this variable is not set, Bash acts as if it had the value
$'\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS'
If the value is null, no timing information is displayed. A trailing newline is added when the format string is displayed.
TMOUT
UID
Related linux commands:
Arguments - bash shell parameters.
export - Set an environment variable.
local - Create a function variable.
env - Display, set, or remove environment variables.
printenv - Print environment variables.
Bash syntax
Windows equivalent commands: Variables - Creating and reading environment variables.