shell指令碼中的函式, shell中的陣列

2021-09-29 19:55:25 字數 2444 閱讀 7004

示例1:

#!/bin/bash #函式的使用;

input()

input 1 a b

[root@second ~]# ./fun.sh

1 a 3 ./fun.sh

示例2:

#!/bin/bash #傳遞乙個引數給函式;

input()

read -p "please input:" n

input

[root@second ~]# ./fun.sh

please input:lksdfjs

lksdfjs

示例3:

#!/bin/bash

input ()

input $1 $2 $3

[root@second ~]# ./fun.sh adkkjl klsklj lkjljljss

adkkjl klsklj lkjljljss 3

示例4

#!/bin/bash

sum()

sum $1 $2

[root@second ~]# bash fun2.sh 7 67786786

67786793

示例5:

#!/bin/bash #輸入網絡卡名,返回ip位址;

ip() #求ip函式;'}

read -p "please input the eth name: " e #互動,輸入網絡卡名字;

myip=`ip $e` #傳遞網絡卡名字給函式,求出並賦值;

echo "$e address is $myip"

please input the eth name: ens33

ens33 address is 192.168.87.150

[root@second ~]# bash fun3.sh

please input the eth name: lo

lo address is 127.0.0.1

[root@second ~]# a=(1 2 3 4 5);      #賦值乙個陣列;

[root@second ~]# echo $ #檢視整個陣列;

1 2 3 4 5

[root@second ~]# echo $ #檢視整個陣列;

1 2 3 4 5

[root@second ~]# echo $ #檢視編號1的元素;

2[root@second ~]# echo $ #檢視編號0的元素;

1[root@second ~]# a[1]=100 #對乙個元素賦值;

[root@second ~]# echo $

100[root@second ~]# echo $

1 100 3 4 5

[root@second ~]# a[5]=6 #增加乙個元素;

[root@second ~]# echo $

1 100 3 4 5 6

[root@second ~]# echo $

6[root@second ~]# unset a[5] #刪除乙個元素;

[root@second ~]# echo $

[root@second ~]# unset a #刪除整個陣列;

[root@second ~]# echo $

[root@second ~]# a=(`seq 1 5`) #使佇列賦值陣列;

[root@second ~]# echo $

1 2 3 4 5

[root@second ~]# echo $ #陣列分片,編號0開始顯示3個;

1 2 3

[root@second ~]# echo $ #編號2開始顯示2個;

3 4[root@second ~]# echo $ #倒數第二個開始顯示2個;

4 5[root@second ~]# echo $

1 2 3 4 5

[root@second ~]# echo $ #替換顯示;

1 2 3 4 100

[root@second ~]# echo $ #內容沒有變;

1 2 3 4 5

[root@second ~]# a[5]=5 #增加元素;

[root@second ~]# echo $

1 2 3 4 5 5

[root@second ~]# a=($) #替換賦值,所有的5都變成100;

[root@second ~]# echo $

1 2 3 4 100 100

SHELL指令碼函式

shll作為指令碼語言,也有自己的函式。但是他有許多與其他語言不同的特點 在這裡,定義了乙個函式,有2個引數,第乙個 陣列,第二個 單個值。這個函式的作用是判斷第二個引數的值是否在第乙個引數 陣列 裡面。bin sh 定義函式 fun function contain do ta array ech...

shell指令碼 函式

函式是乙個指令碼 塊,由使用者對其自定義,可以在指令碼的任意位置建立,按照格式將命令寫入到函式中,系統不會直接執行函式中的命令。如果想要這個函式,只要呼叫這個函式的名稱 只需要輸入名稱 就可以了,而且可以在指令碼的任意位置呼叫,使用函式的好處在於模組化以及 可讀性強。function 函式名稱 可以...

shell指令碼 函式

函式function是由若干條shell命令組成的語句塊,實現 重用和模組化程式設計。它與shell程式形式上是相似的,不同的是它不是乙個單獨的程序,不能獨立執行,而是shell 程式的一部分。函式和shell程式比較相似,區別在於 shell 程式在子shell中執行 而shell函式在當前she...