Introduction to Variables and Parameters

Variable Subsititution

variable1=23
echo variable1
variable1
echo $variable1
23

#!bin/bash

a=375
hello=$a

echo hello
# hello
echo $hello
# 375
echo ${hello} # 375

echo "$hello" # 375
echo "${hello}" # 375

hello="A B C   D"
echo $hello # A B C D
echo "$hello" # A B C   D
# 带引号的会保持原来的空格

echo '$hello' # $hello

numbers="one two three"
other_numbers="1 2 3"
echo "numbers = $numbers"
echo "other_numbers = $other_numbers"

mixed_bag=2\ ---\ Whatever
echo "$mixed_bag"
uninitialized_variable=
# Declaring, but not initializing it
echo "uninitialized_variable = $uninitialized_variable"
# It still has a null value

uninitialized_variable=23 # Set it
unset uninitialized_variable # Unset it

echo

exit 0

Variable Assignment

#!/bin/bash
# Naked variables

echo

# When is a variable "naked", i.e., lacking the '$' in front?
# When it is assigned ,rather than referenced.

# Assignment
a=879
echo "The value of \"a\" is $a"

# Assignment using let
let a=1+2
echo $a

# In a for loop (really, a type of disguised assignment)
echo -n "Values of \"a\" in the loops are"
for a in 7 8 9 10
do
echo -n "$a "
end

echo 
echo

# In a 'read' statement (also a type of assignment)
echo -n "Enter \"a\" "
read a
echo "The value of \"a\" is now $a"

echo

exit 0

#!/bin/bash
a=`echo Hello!`
echo $a
a=`ls -l`
echo $a
echo "$a"

Bash Variables Are Untyped

  • Bash 是无类型的语言,所有的变量都是字符串,当字符串里面都是数字的时候可以进行数字运算
#!/bin/bash
# int-or-string.sh

a=2334
let "a += 1"
echo "a = $a" # 2335
echo

b=${a/23/BB} # BB35
declare -i b # Declare it an integer doen't help
let "b += 1"
echo "b = $b" # b = 1
echo # Bash sets the "integer value" of string to 0

c=BB34
echo "c = $c" # c = BB34
d=${c/BB/23} # Substitute "23" for "BB"
             # This makes d an integer

echo "d = $d"
let "d += 1" # 2335
echo "d = $d"

# What about null variables
e=''
echo "e = $e" # e = 
let "e += 1"
echo "e = $e" # e = 1

Special Variable Types

Local variables
  • Variable visible only within a code block or function
Environmental variables
  • Variables that affect the behavior of the shell and interface

$0 command itself

$1 $2 $3 first second third parameter

$* and $ $@ denote all the positional parameters

$# Number of args passed

Using shift
until [ -z $1 ]
do
echo -n $1
shift
done

shift 3

until [ -z $1 ]
do
echo -n $1
done