Saturday 22 February 2014

BASH variables

bash variables are used to store the useful information referred by the scripts

  1. local variables: declared and used only in the local shall process.
  2. environment variables: used by the login process and the sub process. the environment variables can be used by all editor's, scripts
  3. parameter variables: used to pass the parameters to shell scripts. they are read only.

some examples:
variable=value or ${variable=value} #how to set value to a variable:
echo $variable         #get the value
unset $variable                 #clear the variable
readonly variable #set the variable to readonly (immutable), you need to set the value and set the property to readonly
let a=a+1 # integer operations

by default, the BASH variable is string. default value is null if not declared before. if you have already set a variable to a string, you can still use the variable for integer operations. the variable will be 0 as initial value.

environment variables:

eg: export environment-variables # declare it is a environment variable
you can use env command to show the defined environment variables. To set and unset variables are the same as

there are some important pre-defined environment variables for the users
PWD,OLDPWD: current user location and previous location
PATH: the location shell is going to search for external commands, scripts and executable program
HOME: user's home directory
SHELL: user's default shell (/bin/bash)
USER: user login name such as root
UID: user UID.
PPID: parent PID.
some tips: the child process can inherit the environment variable from parenet process but if the variable is changed in child process, it can't be passed to the parent

~/.bash_profiles: usually where you define your BASH environment variables.
if .bash_profiles is not existing, it will use /etc/profiles as alternative file.
~/.login is used by Cshell, ~./profiles is used by kshell. the variables there can be referred by BASH but strongly not recommended.

parameter variables:


  • $0: the script itself, $1, $2, $3: the first, second and third parameters. ${10}, the 10th parameter
  • $# paramter numbers
  • $* all parameters
  • $? exit code. 0 for successful and 
  • $$ current PID

Quotes in Bash


"" (partially quote): all the characters are treated as normal characters except $ ` and \ . it can also reserve the space in the variable
'' (full quote): all the characters are treated as normal characters.
`command`: use the command as a linux command

No comments:

Post a Comment