Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Unix shell variables


  • Please log in to reply
2 replies to this topic

#1 DarkLordoftheMonkeys

DarkLordoftheMonkeys

    CC Addict

  • Just Joined
  • PipPipPipPipPip
  • 232 posts

Posted 12 November 2009 - 07:15 AM

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.
  • 1
Life's too short to be cool. Be a nerd.

#2 debtboy

debtboy

    CC Devotee

  • Just Joined
  • PipPipPipPipPipPip
  • 499 posts

Posted 12 November 2009 - 01:22 PM

Great Tutorial!! +rep :)
  • 0

#3 nikhilkhullar

nikhilkhullar

    CC Newcomer

  • Just Joined
  • PipPip
  • 20 posts

Posted 22 November 2009 - 12:47 AM

Nice One for beginners... :)
  • 0




Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download