第五章 Shell函數與數組

來源:互聯網
上載者:User

標籤:shell數組 shell函數 shell遍曆數組

5.1 函數

格式:

func() {    command}

樣本1:

#!/bin/bashfunc() {    echo "This is a function."}func# bash test.shThis is a function.

Shell函數很簡單,函數名後跟雙括弧,再跟雙大括弧。通過函數名直接調用,不加小括弧。

樣本2:函數傳回值

#!/bin/bashfunc() {    VAR=$((1+1))    return $VAR    echo "This is a function."}funcecho $?# bash test.sh2

return在函數中是定義狀態傳回值,返回並終止函數,但返回的只能是數字,類似於exit 0。

樣本3:函數傳參

#!/bin/bashfunc() {    echo "Hello $1"}func world# bash test.shHello world

通過Shell位置參數給函數傳參。


部落格地址:http://lizhenliang.blog.51cto.com

QQ群:Shell/Python營運開發群 323779636


5.2 數組

數組是相同類型的元素按一定順序排列的集合。

格式:

array=(元素1 元素2 元素3 ...)

用小括弧初始化數組,元素之間用空格分隔。

定義方法1:初始化數組array=(a b c)定義方法2:建立數組並添加元素array[下標]=元素定義方法3:將命令輸出作為數組元素array=($(command))

數組操作:

擷取所有元素# echo ${array[*]}  # *和@ 都是代表所有元素a b c擷取數組長度# echo ${#array[*]}3擷取第一個元素# echo ${array[0]}a擷取第二個元素# echo ${array[1]}b擷取第三個元素# echo ${array[2]}c添加元素# array[3]=d# echo ${array[*]}a b c d添加多個元素# array+=(e f g)# echo ${array[*]}a b c d e f g刪除a元素# unset array[a]  # 用名字刪除會保留元素下標# echo ${array[*]}b c d e f g刪除第一個元素# unset array[1] # echo ${array[*]}c d e f g

數組下標是以0開始。

樣本1:講seq產生的數字序列迴圈放到數組裡面

#!/bin/bashfor i in $(seq 1 10); do    array[a]=$i    let a++doneecho ${array[*]}# bash test.sh1 2 3 4 5 6 7 8 9 10刪除數組# unset array

樣本2:遍曆數組元素

#!/bin/bashIP=(192.168.1.1 192.168.1.2 192.168.1.3)for ((i=0;i<${#IP[*]};i++)); do    echo ${IP[$i]}done# bash test.sh192.168.1.1192.168.1.2192.168.1.3


本文出自 “李振良的技術部落格” 部落格,請務必保留此出處http://lizhenliang.blog.51cto.com/7876557/1882962

第五章 Shell函數與數組

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.