Unix relies heavily on strings. When a variable is declared it is usually assumed to be a string. There is separate notation for declaring numbers and arrays. If a string is operated on as a number, it will be automatically converted to a number so that the operation may be done. This is because Shell uses weak typing. Unlike other languages, shell variables declared in a script remain after the script completes. To prevent this, type:
unset var;
at the end of the script.
Notation for variables:
Unix variables are set using the syntax:
var=value;
They are accessed with a $ sign:
echo $var;
Variables can also be written using curly bracket notation:
${variable}
This is commonly used for string operators.
Special variables:
$1, $2, $3, etc. - the first, second, third, etc. inputs to the script or function
$0 - the first word typed when calling the script. On my terminal this is always bash.
$# - the number of inputs to the script
$* - a list of all inputs to the script or function
$@ - a list of all inputs to the script or function, individually quoted
$? - the exit status or return value of the last command or function
Environment variables:
These variables are built into the shell:
$LINES - the number of lines in the terminal window
$COLUMNS - the width of the terminal window
$TERM - the name of the terminal
$SHELL - the name of the shell
$PATH - a list of all paths to the current application
$RANDOM - a random number
String operators:
${string:x:y} - substring of string starting at index x and continuing for y characters.
${#string} - the length of string
${string/pattern/new} - replace the first instance of pattern in string with new
${string//pattern/new} - replace all instances of pattern in string with new
Declaring an array:
array[0]=value1;
array[1]=value2;
etc.
array=([0]=value1 [1]=value2 [2]=value3);
Most of the string operators can be applied to arrays. When they are, they operate on the elements of the array, rather than individual characters.
Life's too short to be cool. Be a nerd.
Nice One for beginners...![]()
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks