聯(lián)系我們網(wǎng)頁設計圖片百度seo推廣方案
變量:
命名規(guī)則:
在Shell中,變量名可以由字母、數(shù)字或者下劃線組成,并且只能以字母或者下劃線開頭。對于變量名的長度,Shell并沒有做出明確的規(guī)定。因此,用戶可以使用任意長度的字符串來作為變量名。但是,為了提高程序的可讀性,建議用戶使用相對較短的字符串作為變量名。
在一個設計良好的程序中,變量的命名有著非常大的學問。通常情況下,用戶應該盡可能選擇有明確意義的英文單詞作為變量名,盡量避免使用拼音或者毫無意義的字符串作為變量名。這樣的話,用戶通過變量名就可以了解該變量的作用。
變量定義:
在Shell中,通常情況下用戶可以直接使用變量,而無需先進行定義,當用戶第一次使用某個變量名時,實際上就同時定義了這個變量,在變量的作用域內(nèi),用戶都可以使用該變量。
#!/bin/bash
#########################
#File name:4.sh
#Version:V10.24
#Author: 小🐖
#Email:wgq3135@163.com
#Created time:2023-03-19 15:03:41
#Description:
#########################a=1
b="hello"echo $a
echo $b#RES:
[root@rhel9 01]# bash 4.sh
1
hello
#聲明數(shù)組變量
[root@kittod ~]# declare -a cd='([0]="a" [1]="b" [2]="c")'
[root@kittod ~]# echo ${cd[1]}
b
[root@kittod ~]# echo ${cd[@]}
a b c
注:也可使用env查看環(huán)境變量
只讀變量(常量):
[root@rhel9 myTest]# str="name"
[root@rhel9 myTest]# readonly str
[root@rhel9 myTest]# str="$str++"
-bash: str:只讀變量
位置參數(shù),預定義變量:
許多情況下,Shell腳本都需要接收用戶的輸入,根據(jù)用戶輸入的參數(shù)來執(zhí)行不同的操作。
從命令行傳遞給Shell腳本的參數(shù)又稱為位置參數(shù),Shell腳本會根據(jù)參數(shù)的位置使用不同的位
置參數(shù)變量讀取它們的值。
案例:
#!/bin/bash
#########################
#File name:4.sh
#Version:V10.24
#Author: 小🐖
#Email:wgq3135@163.com
#Created time:2023-03-19 15:03:41
#Description:
#########################echo "first arg:$1"
echo "second arg:$2"
echo "all(*) arg:$*"
echo "all(@) arg:$@"
echo "all arg number:$#"
echo "Program Process Id:$$"#RES:
[root@rhel9 01]# bash 4.sh 5 6
first arg:5
second arg:6
all(*) arg:5 6
all(@) arg:5 6
all arg number:2
Program Process Id:112550
$?案例:
#!/bin/bash
#########################
#File name:5.sh
#Version:V10.24
#Author: 小🐖
#Email:wgq3135@163.com
#Created time:2023-03-19 15:32:33
#Description:
#########################ping -c2 $1 &>/dev/null
if [ $? = 0 ];thenecho "host:$1 is fine"
elseecho "host:$1 is bad"
fi#RES:
[root@rhel9 01]# bash 5.sh www.baidu.com
host:www.baidu.com is fine[root@rhel9 01]# bash 5.sh 192.168.5.1
host:192.168.5.1 is bad
$*與$@的區(qū)別:
[root@rhel9 01]# set -- "i have" a cat
[root@rhel9 01]# echo $#
3
[root@rhel9 01]# echo $*
i have a cat
[root@rhel9 01]# echo $@
i have a cat
[root@rhel9 01]# for i in "$*";do echo $i;done
i have a cat
[root@rhel9 01]# for i in "$@";do echo $i;done
i have
a
cat#RES
$*是將所有參數(shù)作為一個返回值
$@是將每個參數(shù)分別返回