|
Softpanorama |
May the source be with you, but remember the KISS principle ;-)
Softpanorama Search
|
| Recommended Links | Bash tips | BASH Debugging | Command history reuse | Advanced filesystem navigation | ||
| IFS | Dotfiles | Shell Prompts | Annotated List of Bash Enhancements | Humor | Etv | |
Bash variables are untyped and can be used both for arithmetic operations and string parsing. They can be global (external), local to the shell instance and local to the function and built-in.
Access can be read-write or read-only.
Enclosing a referenced value in double quotes (" ") does not interfere with variable substitution. This is called partial quoting, sometimes referred to as "weak quoting". Using single quotes (' ') causes the variable name to be used literally, and no substitution will take place. This is full quoting, sometimes referred to as "strong quoting".
Note that $variable is actually a simplified alternate form of ${variable}. In contexts where the $variable syntax causes an error, the longer form may work
Example 3-5. Variable assignment and substitution
1 #!/bin/bash
2
3 # Variables: assignment and substitution
4
5 a=37.5
6 hello=$a
7 # No space permitted on either side of = sign when initializing variables.
8
9 echo hello
10 # Not a reference.
11
12 echo $hello
13 echo ${hello} #Identical to above.
14
15 echo "$hello"
16 echo "${hello}"
17
18 echo '$hello'
19 # Variable referencing disabled by single quotes,
20 # because $ interpreted literally.
21
22 # Notice the effect of different types of quoting.
23
24 # --------------------------------------------------------------
25
26 # It is permissible to set multiple variables on the same line,
27 # separated by white space. Careful, this may reduce legibility.
28
29 var1=variable1 var2=variable2 var3=variable3
30 echo
31 echo "var1=$var1 var2=$var2 var3=$var3"
32
33 # --------------------------------------------------------------
34
35 echo; echo
36
37 numbers="one two three"
38 other_numbers="1 2 3"
39 # If whitespace within variables, then quotes necessary.
40 echo "numbers = $numbers"
41 echo "other_numbers = $other_numbers"
42 echo
43
44 echo "uninitialized variable = $uninitialized_variable"
45 # Uninitialized variable has null value (no value at all).
46
47 echo
48
49 exit 0
|
| ! | An uninitialized variable has a "null" value - no assigned value at all (not zero!). Using a variable before assigning a value to it will inevitably cause problems. |
May be used for concatenating variables with strings.
1 your_id=${USER}-on-${HOSTNAME}
2 echo "$your_id"
3 #
4 echo "Old \$PATH = $PATH"
5 PATH=${PATH}:/opt/bin #Add /opt/bin to $PATH for duration of script.
6 echo "New \$PATH = $PATH"
|
1 echo ${username-`whoami`}
2 # Echoes the result of `whoami`, but variable "username" is still unset.
|
| ! | This is almost equivalent to ${parameter:-default}. The extra : makes a difference only when parameter has been declared, but is null. |
1 #!/bin/bash
2
3 username0=
4 echo "username0 = ${username0-`whoami`}"
5 # username0 has been declared, but is set to null.
6 # Will not echo.
7
8 echo "username1 = ${username1-`whoami`}"
9 # username1 has not been declared.
10 # Will echo.
11
12 username2=
13 echo "username2 = ${username2:-`whoami`}"
14 # username2 has been declared, but is set to null.
15 # Will echo because of :- rather than just - in condition test.
16
17 exit 0
|
Both forms nearly equivalent. The : makes a difference only when parameter has been declared and is null, as above.
1 echo ${username=`whoami`}
2 # Variable "username" is now set to `whoami`.
|
Both forms nearly equivalent. The : makes a difference only when parameter has been declared and is null, as above.
Both forms nearly equivalent. The : makes a difference only when parameter has been declared and is null, as above.
Example
1 #!/bin/bash
2
3 # Let's check some of the system's environmental variables.
4 # If, for example, $USER, the name of the person
5 # at the console, is not set, the machine will not
6 # recognize you.
7
8 : ${HOSTNAME?} ${USER?} ${HOME} ${MAIL?}
9 echo
10 echo "Name of the machine is $HOSTNAME."
11 echo "You are $USER."
12 echo "Your home directory is $HOME."
13 echo "Your mail INBOX is located in $MAIL."
14 echo
15 echo "If you are reading this message,"
16 echo "critical environmental variables have been set."
17 echo
18 echo
19
20 # The ':' operator seems fairly error tolerant.
21 # This script works even if the '$' omitted in front of
22 # {HOSTNAME}, {USER?}, {HOME?}, and {MAIL?}. Why?
23
24 # ------------------------------------------------------
25
26 # The ${variablename?} construction can also check
27 # for variables set within the script.
28
29 ThisVariable=Value-of-ThisVariable
30 # Note, by the way, that string variables may be set
31 # to characters disallowed in their names.
32 : ${ThisVariable?}
33 echo "Value of ThisVariable is $ThisVariable".
34 echo
35 echo
36
37 # If ZZXy23AB has not been set...
38 : ${ZZXy23AB?}
39 # This will give you an error message and terminate.
40
41 echo "You will not see this message."
42
43 exit 0
|
Version 2 of bash adds additional options.
Example
1 #!/bin/bash
2
3 # rfe
4 # ---
5
6 # Renaming file extensions.
7 #
8 # rfe old_extension new_extension
9 #
10 # Example:
11 # To rename all *.gif files in working directory to *.jpg,
12 # rfe gif jpg
13
14 if [ $# -ne 2 ]
15 then
16 echo "Usage: `basename $0` old_file_suffix new_file_suffix"
17 exit 1
18 fi
19
20 for filename in *.$1
21 # Traverse list of files ending with 1st argument.
22 do
23 mv $filename ${filename%$1}$2
24 # Strip off part of filename matching 1st argument,
25 # then append 2nd argument.
26 done
27
28 exit 0
|
If replacement is omitted, then the first match of patt is replaced by nothing, that is, deleted.
Similar to above, if replacement is omitted, then all occurrences patt are replaced by nothing, that is, deleted.
Example
1 #!/bin/bash
2
3 var1=abcd-1234-defg
4 echo "var1 = $var1"
5
6 t=${var1#*-*}
7 echo "var1 (with everything, up to and including first - stripped out) = $t"
8 t=${var1%*-*}
9 echo "var1 (with everything from the last - on stripped out) = $t"
10
11 echo
12
13 path_name=/home/bozo/ideas/thoughts.for.today
14 echo "path_name = $path_name"
15 t=${path_name##/*/}
16 # Same effect as t=`basename $path_name`
17 echo "path_name, stripped of prefixes = $t"
18 t=${path_name%/*.*}
19 # Same effect as t=`dirname $path_name`
20 echo "path_name, stripped of suffixes = $t"
21
22 echo
23
24 t=${path_name:11}
25 echo "$path_name, with first 11 chars stripped off = $t"
26 t=${path_name:11:5}
27 echo "$path_name, with first 11 chars stripped off, length 5 = $t"
28
29 echo
30
31 t=${path_name/bozo/clown}
32 echo "$path_name with \"bozo\" replaced by \"clown\" = $t"
33 t=${path_name/today/}
34 echo "$path_name with \"today\" deleted = $t"
35 t=${path_name//o/O}
36 echo "$path_name with all o's capitalized = $t"
37 t=${path_name//o/}
38 echo "$path_name with all o's deleted = $t"
39
40 exit 0
|
There are several built-in variables which are set or used by Bash:
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.
COLUMNS
select builtin command to determine the terminal
width when printing selection lists. Automatically set upon receipt of a
SIGWINCH.
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 (see section
8.6 Programmable Completion).
COMP_LINE
COMP_POINT
${#COMP_LINE}.
This variable is available only in shell functions and external commands
invoked by the programmable completion facilities (see section
8.6 Programmable Completion)
COMP_WORDS
COMPREPLY
DIRSTACK
dirs builtin. Assigning to members of this array variable may
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:~'
FUNCNAME
FUNCNAME
have no effect and return an error status. If FUNCNAME is unset,
it loses its special properties, even if it is subsequently reset.
GLOBIGNORE
GLOBIGNORE, it is removed
from the list of matches.
GROUPS
GROUPS have no effect and return
an error status. 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.
HISTCONTROL
HISTCONTROL.
HISTFILE
HISTFILESIZE
HISTIGNORE
HISTCONTROL are applied. In addition to the normal shell
pattern matching characters, `&' matches the previous history
line. `&' may 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.
HISTSIZE
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
LANGLC_.
LC_ALL
LANG and any other
LC_ variable specifying a locale category.
LC_COLLATE
LC_CTYPE
LC_MESSAGES
LC_NUMERIC
LINENO
LINES
select builtin command to determine the column
length for printing selection lists. Automatically set upon receipt of a
SIGWINCH.
MACHTYPE
MAILCHECK
MAILPATH or MAIL variables. The
default is 60 seconds. When it is time to check for mail, the shell does
so before displaying the primary prompt. If this variable is unset, or set
to a value that is not a number greater than or equal to zero, the shell
disables mail checking.
OLDPWD
cd builtin.
OPTERR
getopts builtin command.
OSTYPE
PIPESTATUS
POSIXLY_CORRECT
bash starts, the
shell enters POSIX mode (see section
6.11 Bash POSIX Mode) before reading the startup files, as if the
`--posix' invocation option had been supplied. If it is set
while the shell is running, bash enables POSIX mode, as if
the command
|
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 (see section
4.3 The Set Builtin). 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
The optional p is a digit specifying the precision, the number of fractional digits after a decimal point. A value of 0 causes no decimal point or fraction to be output. At most three places after the decimal point may be specified; values of p greater than 3 are changed to 3. If p is not specified, the value 3 is used.
The optional 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
|
TMOUT
UID
Copyright © 1996-2009 by Dr. Nikolai Bezroukov. www.softpanorama.org was created as a service to the UN Sustainable Development Networking Programme (SDNP) in the author free time. Submit comments This document is an industrial compilation designed and created exclusively for educational use and is placed under the copyright of the Open Content License(OPL). Site uses AdSense so you need to be aware of Google privacy policy. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.
Disclaimer:
Last modified: August 15, 2009