Skip to content

Latest commit

 

History

History
123 lines (89 loc) · 3.36 KB

File metadata and controls

123 lines (89 loc) · 3.36 KB

4.2. Variable Assignment

第四章第二節:變數值

the assignment operator (no space before and after)

指定變數值的運算子(運算子前後都不能有空格)

Caution Do not confuse this with = and -eq, which test, rather than assign!

注意:這是變數賦值,別跟 test 指令的 = 與 -eq 運算子混淆!

Note that = can be either an assignment or a test operator, depending on context.

請注意 = 可以是一個賦值運算子或一個 test 運算子,依所處的內容而意義有所不同。

Example 4-2. Plain Variable Assignment

範例 4-2. 普通的變數賦值

#!/bin/bash
# Naked variables
# 裸體變數

echo

# When is a variable "naked", i.e., lacking the '$' in front?
# 變數何時為 "裸體" 的呢?也就是前面少個錢字號 '$' 的時候。
# When it is being assigned, rather than referenced.
# 當它被賦值而不是被參考的時候。

# Assignment
# 賦值:
a=879
echo "The value of \"a\" is $a."

# Assignment using 'let'
# 使用 'let' 賦值:
let a=16+5
echo "The value of \"a\" is now $a."

echo

# In a 'for' loop (really, a type of disguised assignment):
# 於 'for' 迴圈中 (真的啦,此為隱含賦值的一種型式):
echo -n "Values of \"a\" in the loop are: "
for a in 7 8 9 11
do
  echo -n "$a "
done

echo
echo

# In a 'read' statement (also a type of assignment):
# 於 'read' 敘述 (這也是賦值的一種型式):
echo -n "Enter \"a\" "
read a
echo "The value of \"a\" is now $a."

echo

exit 0

Example 4-3. Variable Assignment, plain and fancy

範例 4-3. 普通的與花俏的變數賦值

#!/bin/bash
a=23              # Simple case
                  # 普通的例子
echo $a
b=$a
echo $b

# Now, getting a little bit fancier (command substitution).
# 現在來點花俏的吧! (指令替換(命令結果代換))

a=`echo Hello!`   # Assigns result of 'echo' command to 'a' ...
                  # 'echo' 指令結果將賦值到 'a' ...
echo $a
# Note that including an exclamation mark (!) within a
#+ command substitution construct will not work from the command-line,
#+ since this triggers the Bash "history mechanism."
# Inside a script, however, the history functions are disabled by default.
# 注意:內含驚歎號 (!) 的指令替換結構在命令列上將會失效,
# 因為會觸發 Bash 的 "歷史機制"。
# 不過,在腳本裡面時,歷史功能預設是關閉的。

a=`ls -l`         # Assigns result of 'ls -l' command to 'a'
                  # 'ls -l' 指令結果將賦值到 'a'
echo $a           # Unquoted, however, it removes tabs and newlines.
                  # 然而,若未使用引號包住,
                  # 則變數值裡的 tabs (定位字元) 跟 newlines (換行字元) 將會被移除。
echo
echo "$a"         # The quoted variable preserves whitespace.
                  # (See the chapter on "Quoting.")
                  # 若有引號包住,則變數裡的空白字元將被保留 (含空格、定位、換行…等)。
                  # (詳情請參照 "引號" 章節。)


exit 0

Variable assignment using the $(...) mechanism (a newer method than backquotes).

使用比反引號 `` 更新式的 $(...) 的變數賦值方式。

This is likewise a form of command substitution.

同樣地這也是一種指令替換的型式。

# From /etc/rc.d/rc.local
R=$(cat /etc/redhat-release)
arch=$(uname -m)