Changes

Jump to: navigation, search

BASH Variables

1,008 bytes added, 22:17, 21 September 2008
no edit summary
[[BASH]] supports one type of variable: a string. Variables may be interpreted as integers or booleans (True/False) when appropriate.
= Creating or Assigning a Variable =
COLOUR="Red"
NAME="Jason Smith"
EMAIL="jsmith@example.com>"
Variable names must start with a letter and contain only letters, underscores, and digits. Variable names are case-sensitive, and UPPERCASE is often used to make it easy to distinguish between variable names and commands and arguments.
echo "Hooray!"
fi
 
Variables are interpolated when in double-quotes, but not when they are in single-quotes:
 
$ X="Test"
$ echo "$X"
Test
$ echo '$X'
$X
$ echo $X
Test
 
One advantage to using double-quotes is that the variable value will be treated as a single argument even when it contain spaces. For example:
 
$ touch "test file"
$ NAME="test file"
$ rm $NAME
rm: cannot remove `test': No such file or directory
rm: cannot remove `file': No such file or directory
$ rm "$NAME"
 
You may optionally place the variable name within curly-braces (useful if there is text immediately after the variable name):
 
NUMBER="12"
echo "You are in ${NUMBER}th place!"
 
= Adding to a Variable =
 
To add to a variable, assign a value to it which contains the existing value plus new data. For example, to add ":." to the end of the PATH variable:
 
PATH="$PATH:."
= Exporting Variables =
|-
|$RANDOM
|Random integer(usually in the range 0-327687).
|}
|-
|$SHELL
|Absolute pathname of the default shell for the current user.
|-
|$HOSTNAME
|Name of the host (computer) on which the shell is executing.
|-
|$PS1
|Primary prompt, used by the shell to request a command from the user.
|-
|$PS2
|Secondary prompt, used to request additional info from the user.
|-
|$PS3
|3rd prompt (rarely used).
|-
|$PS4
|4th prompt (rarely used).
|}
 
[[Category:BASH]][[Category:Linux]]

Navigation menu