Bash Programming Cheat Sheet


Bash Programming Cheat Sheet
Page 1 of 4
Updated: 02/03/2008 00:46:31
Bash Programming Cheat Sheet
Written By:
A quick cheat sheet for programmers who want to do shell scripting. This is not intended to teach programming, etc.
but it is intended for a someone who knows one programming language to begin learning about bash scripting.
All bash scripts must tell the o/s what to use as the interpreter. The first line of any script should be:
You must make bash scripts executable.
chmod +x filename
Create a variable - just assign value. Variables are non-datatyped (a variable can hold strings, numbers, etc. with out
being defined as such).
Access a variable by putting $ on the front of the name
echo $varname
Values passed in from the command line as arguments are accessed as $# where #= the index of the variable in the
array of values being passed in. This array is base 1 not base 0.
command var1 var2 var3 .... varX
$1 contains whatever var1 was, $2 contains whatever var2 was, etc.
Built in variables:
$1-$N Stores the arguments (variables) that were passed to the shell program from the command line.
Stores the exit value of the last command that was executed.
Stores the first word of the entered command (the name of the shell program).
Stores all the arguments that were entered on the command line ($1 $2 ...).
"$@" Stores all the arguments that were entered on the command line, individually quoted ("$1" "$2" ...).
Quote Marks
Regular double quotes ("like these") make the shell ignore whitespace and count it all as one argument being passed or
string to use. Special characters inside are still noticed/obeyed.
Single quotes 'like this' make the interpreting shell ignore all special characters in whatever string is being passed.
The back single quote marks (`command`) perform a different function. They are used when you want to use the results
of a command in another command. For example, if you wanted to set the value of the variable contents equal to the list
of files in the current directory, you would type the following command: contents=`ls`, the results of the ls program are
put in the variable contents.


00 votes

Related Articles

Related forms

Related Categories

Parent category: Education
Page of 4