天天看點

一組Linux Shell Scripting小練習

# linux shell将字元串分割成數組

1

2

<code>result=$(facter | </code><code>awk</code> <code>'/ipaddress/ &amp;&amp; !/ipaddress_lo/ {print $1 " " $3}'</code><code>)</code>

<code>array=($result)</code>

# 判斷一個變量是否存在(不是判斷是否為空)

<code>if</code> <code>[ -z ${var+x} ]; </code><code>then</code> <code>echo</code> <code>"var is unset"</code><code>; </code><code>else</code> <code>echo</code> <code>"var is set to '$var'"</code><code>; </code><code>fi</code>

# 判斷一個變量是否為空

<code>if</code> <code>[ </code><code>"$var x"</code> <code>= </code><code>" x"</code> <code>]; </code><code>then</code> <code>echo</code> <code>"var is empty"</code><code>; </code><code>else</code> <code>echo</code> <code>"var is set to '$var'"</code><code>; </code><code>fi</code>

<code>if</code> <code>[ -z $var ]; </code><code>then</code> <code>echo</code> <code>"var is empty"</code><code>; </code><code>else</code> <code>echo</code> <code>"var is set to '$var'"</code><code>; </code><code>fi</code>

#系統變量用後還原

# 關于ifs的定義:ifs,internal field separator

# an internal field separator (ifs) is an environment variable that stores delimiting characters.

# it is the default delimiter string used by a running shell environment.

# "$*" expands as "$1c$2c$3", where c is the first character of ifs

# when the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the ifs special variable.

# that is, "$*" is equivalent to "$1c$2c...", where c is the first  char‐acter of the value of the ifs variable. 

# if ifs is unset, the parameters are separated by spaces.  if ifs is null, the parameters are joined without intervening separators.

3

4

5

6

7

<code>oldifs=</code><code>"$ifs"</code> 

<code>ifs=</code><code>" "</code> 

<code>ifs=</code><code>"$oldifs"</code> 

<code>for</code> <code>i </code><code>in</code> <code>${array[@]}; </code><code>do</code>

<code>echo</code> <code>$i</code>

<code>done</code>

# 使用facter擷取一組key-value

# facter的輸出有換行符,必須把換行符替換成空格

# 将換行符替換成空格可以使用awk或sed

# awk -v rs="" '{gsub("\n"," ");print}'

# echo -e "2 \n1" | sed ':a;n;$!ba;s/\n/ /g'

<code>result=$(facter | </code><code>awk</code> <code>'/ipaddress/ &amp;&amp; !/ipaddress_lo/ {print $1 " " $3}'</code> <code>| </code><code>awk</code> <code>-</code><code>v</code> <code>rs=</code><code>""</code> <code>'{gsub("\n"," ");print}'</code><code>)</code>

<code>array_length=${</code><code>#array[@]}</code>

# 輸出key

<code>for</code> <code>(( i = 0; i &lt; $array_length; i=i+2 )); </code><code>do</code>

<code>    </code><code>echo</code> <code>${array[$i]}</code>

# 輸出value

<code>for</code> <code>(( i = 1; i &lt; $array_length; i=i+2 )); </code><code>do</code>

# 輸出key-value

<code>    </code><code>j=$i+1</code>

<code>    </code><code>echo</code> <code>"${array[$i]} - ${array[$j]}"</code>

--end--

繼續閱讀