Bash Reference

Posted on Posted in Linux-Ubuntu, Programming

The Shebang (#!)

  • In the beginning, first line of the file, no spaces.
  • Next, absolute path to the script interpreter (might change, but better to execute anywhere), in this case: /bin/bash
  • Call to the script does not look in current directory, so ./ is necessary or it has to be included in PATH

Special System Variables

  • $0 – The name of the Bash script.
  • $1 – $9 – The first 9 arguments to the Bash script.
  • $# – How many arguments were passed to the Bash script.
  • $@ – All the arguments supplied to the Bash script.
  • $? – The exit status of the most recently run process.
  • $$ – The process ID of the current script.
  • $USER – The username of the user running the script.
  • $HOSTNAME – The hostname of the machine the script is running on.
  • $SECONDS – The number of seconds since the script was started.
  • $RANDOM – Returns a different random number each time is it referred to.
  • $LINENO – Returns the current line number in the Bash script.

Variable Assignment


  • No $ sign at the beginning.
  • No space at either side of the equal.
  • Case sensitive.
  • Variables set by a program must not have = or nul, but for the shell environment, they have more limitations: consist solely of uppercase letters, digits, and the ‘_’ (underscore) and do not begin with a digit. User variables follow the C variable definition rules (lowercase allowed). Regex:[a-zA-Z_]+[a-zA-Z0-9_]*


Bash uses a space to determine separate items. When we enclose our content in quotes we are indicating to Bash that the contents should be considered as a single item. You may use single quotes ( ‘ ) or double quotes ( ” ).

  • Single quotes will treat every character literally.
  • Double quotes will allow you to do substitution (that is include variables within the setting of the value) nvar="Add $var"

Command Substitution

The output of command or program is saved into a variable variable=$(command) ex. directoryls=$(ls -al)
Adequate for just one word or line, newlines are removed and stored in a single line in the variable.

Exporting Variables

Exporting variables make them available for child subprocesses created in the running script
export var
Note: exporting a variable to the environment only works in the interactive console, not in scripts. To export it, modify /etc/environment from a script


    • let expression Make a variable equal to an expression. Ex. let a=5+4
    • expr expression Print out the result of the expression.
    • $(( expression )) Return the result of the expression.
    • ${#var} Return the length of the variable var.
Operator Operation
+, -, /*, / addition, subtraction, multiply, divide
var++ Increase the variable var by 1
var– Decrease the variable var by 1
% Modulus (Return the remainder after division)


Control Statements

if [ <some test> ] then
elif [ <some test> ] then
<different commands>
<other commands>

case <variable> in
<pattern 1>)
<pattern 2>)
<other commands>


while [ <some test> ] do


until [ <some test> ] do


for var in <list>

SELECT Present list items for selection with a number before each item
select var in <list>

break Goes out of the loop
continue Goes to the beginning of next iteration
Range ex. for value in {1..5}
Range with step ex. for value in {10..0..2}

Operator Description
&& And
|| Or
-n STRING The length of STRING is greater than zero.
-z STRING The lengh of STRING is zero (ie it is empty).
STRING1 != STRING2 STRING1 is not equal to STRING2
INTEGER1 -eq INTEGER2 INTEGER1 is numerically equal to INTEGER2
INTEGER1 -gt INTEGER2 INTEGER1 is numerically greater than INTEGER2
INTEGER1 -lt INTEGER2 INTEGER1 is numerically less than INTEGER2
-d FILE FILE exists and is a directory.
-e FILE FILE exists.
-r FILE FILE exists and the read permission is granted.
-s FILE FILE exists and it’s size is greater than zero (ie. it is not empty).
-w FILE FILE exists and the write permission is granted.
-x FILE FILE exists and the execute permission is granted.



function <name> or <name>() {  <commands>  } Create a function called name. Must appear in the script before any calls to the function. Arguments are passed as to the script $1, $2…
return <value> Exit the function with a return status of value.
local <name>=<value>  Create a local variable within a function.
command <command> Run the command with that name as opposed to the function with the same name.

print_something () {
echo Hello $1
return 5
print_something Mars
print_something Jupiter
echo The previous function has a return value of $?

Hello Mars
Hello Jupiter
The previous function has a return value of 5


# Print message in center of terminal
cols=$( tput cols )
rows=$( tput lines )
half_input_length=$(( $input_length / 2 ))
middle_row=$(( $rows / 2 ))
middle_col=$(( ($cols / 2) - $half_input_length ))
tput clear
tput cup $middle_row $middle_col
tput bold
echo $@
tput sgr0
tput cup $( tput lines ) 0

tput cols will tell us how many columns the terminal has.
tput lines will tell us how many lines (or rows) the terminal has.
Take all the command line arguments and assign them to a single variable message.
Find out how many characters are in the string message. We had to assign all the input values to the variable message first as ${#@} would tell us how many command line arguments there were instead of the number of characters combined.
We need to know what 1/2 the length of the string message is in order to center it.
Calculate where to place the message for it to be centered.
tput clear will clear the terminal.
tput cup will place the cursor at the given row and column.
tput bold will make everything printed to the screen bold.
Now we have everything set up let’s print our message.
tput sgr0 will turn bold off (and any other changes we may have made).
tput cup $( tput lines ) 0Place the prompt at the bottom of the screen.

Bash Tutorial
Advanced Bash Scripting