linux shell 提取變數 變數傳參

2021-07-11 18:31:03 字數 2810 閱讀 7775

已知:/etc/hosts的內容為

192.168.1.11  oldboy11.etiantian.org

192.168.1.21  oldboy21.etiantian.org

192.168.1.31  oldboy31.etiantian.org

#192.168.1.111  oldboy111.etiantian.org

請用shell指令碼實現,怎麼才能在輸入ip後找到/etc/hosts裡對應的唯一的hostname?

解答:法1)指令碼過濾法

[root@old_boy scripts]# cat judgehost.sh  

#!/bin/bash 

echo "please input ip address:"

read ip 

[ -n "`grep "$ip " /etc/hosts`" ] && \  #注意前面的過濾條件結尾帶有空格。 

echo "the hostname is: `grep "$ip " /etc/hosts |awk ''`" || \ 

echo "the ip is invalid"

法2)指令碼精確匹配法:

法3)awk精確匹配:

準備:[root@old_boy scripts]# tail -4 /etc/hosts

192.168.1.11  oldboy11.etiantian.org

192.168.1.111  oldboy111.etiantian.org

192.168.1.21  oldboy21.etiantian.org

192.168.1.31  oldboy31.etiantian.org

指令碼:[root@old_boy scripts]# cat awkhost1.sh  

awk 'begin ' /etc/hosts 

法4)awk精確匹配法

[root@old_boy scripts]# cat awkhost2.sh  

awk '' /etc/hosts 

執行結果:

[root@old_boy scripts]# awkhost2.sh 192.168.1.11

oldboy11.etiantian.org

[root@old_boy scripts]# awkhost2.sh 192.168.1.21

oldboy21.etiantian.org

[root@old_boy scripts]# awkhost2.sh 192.168.1.311

法5)awk過濾法

法6)awk過濾法

[root@old_boy scripts]# cat awkhost5.sh  

awk ''  /etc/hosts ##如果檔案第一列包含命令列第乙個引數字元則列印第二列 

執行結果: 

[root@old_boy scripts]# awkhost5.sh 192.168.1.31 

oldboy31.etiantian.org 

[root@old_boy scripts]# awkhost5.sh 192.168.1.11 

oldboy11.etiantian.org 

oldboy111.etiantian.org ------>這裡有bug了。 

[root@old_boy scripts]# awkhost5.sh 192.168.1.21 

oldboy21.etiantian.org 

改進下來排除bug: 

[root@old_boy scripts]# cat awkhost5-1.sh  

awk ''  /etc/hosts ==>用上面加空格的思路不對。 

[root@old_boy scripts]# cat awkhost5-1.sh  

awk ''  /etc/hosts #增加乙個正規表示式$ 

執行結果: 

[root@old_boy scripts]# awkhost5-1.sh 192.168.1.21 

oldboy21.etiantian.org 

[root@old_boy scripts]# awkhost5-1.sh 192.168.1.11 

oldboy11.etiantian.org 

[root@old_boy scripts]# awkhost5-1.sh 192.168.1.31 

oldboy31.etiantian.org

法7)awk -v精確匹配法

命令列測試: 

[root@old_boy scripts]# awk -v p=192.168.1.21 '$1 == p' /etc/hosts 

oldboy21.etiantian.org 

[root@old_boy scripts]# awk -v p=192.168.1.11 '$1 == p' /etc/hosts 

oldboy11.etiantian.org 

[root@old_boy scripts]# awk -v p=192.168.1.11 '$1 == p ' /etc/hosts 

oldboy11.etiantian.org 

實測指令碼:

[root@old_boy scripts]# cat awkhost6.sh  

#!/bin/bash 

#p=$1 

#awk -v p="$p" '$1 == p' /etc/hosts 

awk -v p="$1" '$1 == p' /etc/hosts

法8:精確匹配簡單的寫法

法9:學生的乙個不成熟的實現法

老男孩老師改進後

for 變數 變數 形式 詳解

listlsit content.getheaders get set cookie for string val lsit 即形如 for 變數 變數 形式 for each是jdk5.0新增加的乙個迴圈結構,可以用來以此處理陣列中的每個元素 其他型別的元素集合也可以 而不用為指定下標而分心。集合...

20150527常量變數

main.c ios150527 created by peng junlong on 15 5 27.include void changliangbian int main int argc,const char argv 常量 變數 常量 是c語言中最基本的元素,包括 字元常量,整型常量,浮點...

Swift 常量變數

main.swift swift 常量變數 created by dingkang on 15 12 15.import foundation 常量 在程式執行期間,不可以改變的量,稱之為常量。變數 在程式執行過程中,其值可以任意改變的量稱之為變數。變數和常量一樣,在使用之前都要進行生宣告和自定義 ...