הלינקייה: מגזין חודשי למפתחים

רוצה לשמוע על כל האירועים, המדריכים, הקורסים והמאמרים שנכתבו החודש ?
הלינקייה הינו מגזין חופשי בעברית שמשאיר אותך בעניינים.
בלי ספאם. בלי שטויות. פעם בחודש אצלך בתיבה.

Variables

Bash provides us with two types of variables. The normal (scalar) variables and array variables.
We'll start with the scalars.

A variable in bash is defined by assigning a value to it, such as

# This sets the variable named x to the value 3
x=3

# And this sets the variable named y to the value 7
y=7

Note: The tokens must not be separated using a space, i.e. this will not work: x = 3

Arrays

The second type of variable in bash is an array. Arrays are sequences of scalars, which can be accessed by an index.
Here's how we set an array value in bash

# We can use the paren notation on the right
arr=(2 4 6 8 10)

# We can use the bracket notation on the left. If 
# the array does not exists, it will autovivify.
arr[0]=2
arr[1]=4
arr[2]=6

Variable Substitution

Variables are substituted by the shell to the current value by prefixing them with a $ sign. Variables substitution is performed by the shell before a line is executed.

# prints Ynon
  name=Ynon
  echo $name

# runs ls -l -r -t. Note the quoting.
  args="-l -r -t"
  ls $args

# And, we can have indirect variables, such as this:
# (It only goes one level though)
  name=Ynon
  field=name
  # prints Ynon
  echo ${!field}

Using arrays is performed with the braces notation. The special * character exapnds to all the elements in the array

  arr=(2 4 6 8 10)

# prints 6
  echo ${arr[2]}

# prints 2 4 6 8 10
  echo ${arr[*]}

Readonly Variables

To declare a variable read-only, use the readonly keyword.

  foo=bar

# prints bar
  echo $foo

# prints: -bash: foo: readonly variable
  set foo=2

# still prints bar
  print $foo

Reading From The User

In bash, the read builtin is used for reading from standard input, or from a file handle. The read builtin can read multiple words of input, or an array to store all the words.
Read supports prompting the user for the input, turning on or off text echo, and use timeouts to limit response time.

Here is how we use read to read input from a user:

# prints "Who's There ?" and wait for a user name. That user name will
# be stored as $name variable. Note that user name is a single word
  read -p "Who\'s There ?" name

# prints "Full Name:" and wait for a first name and last name (two
# words). 
  read -p "Full Name: " first last

# Takes a list of names from a user and store it in an array
  read -p "Participants (separated by spaces): " -a participants

Special Variables

Bash provides some useful special variables for shell scripts, which are summarized below:

  1. $0,$1..$n Positional Variables. Each includes the n-th argument to the current script
  2. $# Positional variables count
  3. $? Return status of the last executed command
  4. $$ Process id of the current shell
  5. $! Process id of the last background process executed