1. 程式人生 > >12、bash腳本變量總結

12、bash腳本變量總結

bash變量總結

bash編程之變量(我們現在要總結了)
1、bash的內置變量:全大寫的,如下的一些變量
PATH PS1 HOSTNAME UID HISTFILE HISTSIZE HISTEILESIZE HISTCONTROL(命令是如何保存在命令歷史中的)
$BASH:bash二進制程序文件的路徑
$BASH_SUBSHELL:子shell的層次
$BASH_VERSION(bash的4以後支持數組關聯的)
$EDITOR:默認編輯器
$EUID:有效的用戶ID
[root@www ~]# echo $EUID
0
[test@www ~]$ echo $EUID
503
$UID:當前用戶的ID號
$FUNCNAME:當前函數的名稱
$GROUPS:當前用戶顯示的組
$HOME:當前用戶的家目錄
$HOSTTYPE:主機架構類型,用來識別系統硬件
$MACHTYPE:平臺類型,系統平臺依賴的編譯平臺
[test@www ~]$ echo $MACHTYPE
x86_64-redhat-linux-gnu
[test@www ~]$ echo $HOSTTYPE
x86_64
[test@www ~]$ echo $OSTYPE
linux-gnu
$OSTYPE:OS系統類型

$IFS(內部的域分隔符):輸入數據時的字段分隔符,默認是空白符(空格、制表符、換行符)

$OLDPWD:上次使用的目錄
$PWD:當前目錄

技術分享圖片

$PPID:父進程

$PS1:主提示符

$PS2:第二提示符,主要用於補充完全命令輸入時的提示符

技術分享圖片

$PS3:第三提示符,用於select命令(這個是菜單生成器)中
$PS4:第四提示符,當使用-X選項調用腳本時,顯示的提示符,默認為+號

$SECONDS:當前腳本(當前shell)已經運行的時長
[root@www ~]# echo $SECONDS
10
[root@www ~]# echo $SECONDS
11
$SHLVL:shell的級別。bash別嵌入的深度

2、特殊變量:$0:腳本名稱自身
$1,$2。。。。:位置參數
$#:命令行參數個數
$*:所有的參數,被當作一個字符串
$@:所有的參數,每個參數都是一個獨立的字符串
br/>$0:腳本名稱自身

$1,$2。。。。:位置參數
$#:命令行參數個數
$*:所有的參數,被當作一個字符串
$@:所有的參數,每個參數都是一個獨立的字符串
$!:運行於後臺的最後一個作業的PID
$_:上一條命令的最後一個參數的值

技術分享圖片

   $?:上一條命令狀態的返回值
   $$:腳本自身的PID

技術分享圖片

bashell就會推出了
操作變量:
${#var} :返回變量中字符串的長度

技術分享圖片

${var}:變量引用(變量替換的),這個用的是比較多的
${var:-default}:如果var沒有聲明或者為空,則返回default字串,否則返回var自身的值
${var:+default}:如果var沒有聲明或者為空,則返回空字串,否則返回default的值

${var:=default}:如果var沒有聲明或者為空,則返回default字串,並且將default賦值給var,否則返回var自身的值

技術分享圖片

${var:?default}:如果var沒有聲明或者為空,則以default為錯誤信息返回,否則

返回var自身的值
[root@www ~]# name=jerry
[root@www ~]# echo ${name:?tom}
jerry
[root@www ~]# unset name
[root@www ~]# echo ${name:?tom}
-bash: name: tom
[root@www ~]#

子串削除:
${varilable#pattern}: 查找variable中自左而右第一次被pattern匹配到的串,將此串及向左的所有內容都刪除
${varilable##
pattern}: 查找variable中自左而右最後一次被pattern匹配到的串,將此串及向左的所有內容都刪除

技術分享圖片

${varilable%pattern}:查找variable中自右而左第一次被pattern匹配到的串,將此串及向右的所有內容都刪除
${varilable%%pattern
}:查找variable中自右而左最後一次被pattern匹配到的串,將此串及向右的所有內容都刪除

技術分享圖片

字串消除取子串:
${variable:pos}: 偏移pos個字符,取余下的子串
name=jerry, ${name:2}結果為rry
${variable:pos:num}: 偏移pos個字符,取num個字符長度的子串
name=‘hello world‘, ${name:2:5}結果為“llo w”
字符串處理,將來在bash中經常用的
bash能力分為三個最為重要:
字符串能力
grep,awk,sed
腳本整體的框架能力
${var#word}:查找var中自左而右第一個被word匹配到的串,並將此串及向左的所有內容都刪除
${var#
word}:查找var中自左而右最後一次被word匹配到的串,並將此串及向左的所有內容都刪除
${var%word}:查找var中自右而左第一個被word匹配到的串,並將此串及向右的所有內容都刪除
${var%%word
}:查找var中自右而左最後一次被word匹配到的串,並將此串及向右的所有內容都刪除

取字串:
  ${var:pos}:偏移pos個字符,取余下的字串
   name=jerry,${name:2}結果為rry
  ${var:pos:num}偏移pos個字符,取num個字符長度的字串
    name=‘hello world‘ ${name:2:5}結果為llo w

子串替換
  ${var/Pattern/Replaceplacement} :以Pattern為模式匹配var中的字串,將第一次匹配到的替換為Replaceplacement
  ${var//Pattern/Replaceplacement} :以Pattern為模式匹配var中的字串,將全部匹配到的替換為Replaceplacement6

技術分享圖片

聲明變量:(bash中不聲明變量也是可以使用過的,但是聲明的話,聲明的位置,決定了他的作用域)
declare
-i:×××
-a:數值
-x:環境變量
-r:只讀變量,不能撤銷,不能修改,相當於readonly命令(a=3 ; readonly a)
-f:聲明函數

技術分享圖片

OpenSSH:
ssh OpenSSH
安裝配置dropbear(在嵌入式系統使用,輕量級的,能夠遠程的,功能比較強大)
可以代替Openssh
1.編譯安裝
tar
cd
./configure
make PROGRMS="dropbear dbclient dropberkey scp"
make PROGRMS="dropbear dbclient dropberkey scp" install
make clean(可以清楚此前編譯的結果的)
2.服務腳本
/etc/rc.d/init.d/dropbear
#!/bin/bash
#

description: dropbear ssh daemon

chkconfig: 2345 66 33

#
dsskey=/etc/dropbear/dropbear_dss_host_key
rsakey=/etc/dropbear/dropbear_rsa_host_key
lockfile=/var/lock/subsys/dropbear
pidfile=/var/run/dropbear.pid
dropbear=/usr/local/sbin/dropbear
dropbearkey=/usr/local/bin/dropbearkey

[ -r /etc/rc.d/init.d/functions ] && . /etc/rc.d/init.d/functions

[ -r /etc/sysconfig/dropbear ] && . /etc/sysconfig/dropbear

keysize=${keysize:-1024}
port=${port:-22}

gendsskey() {
[ -d /etc/dropbear ] || mkdir /etc/dropbear
echo -n "Starting generate the dss key: "
$dropbearkey -t dss -f $dsskey &> /dev/null
RETVAL=$?
if [ $RETVAL -eq 0 ]; then
success
echo
return 0
else
failure
echo
return 1
fi
}

genrsakey() {
[ -d /etc/dropbear ] || mkdir /etc/dropbear
echo -n "Starting generate the rsa key: "
$dropbearkey -t rsa -s $keysize -f $rsakey &> /dev/null
RETVAL=$?
if [ $RETVAL -eq 0 ]; then
success
echo
return 0
else
failure
echo
return 1
fi
}

start() {
[ -e $dsskey ] || gendsskey
[ -e $rsakey ] || genrsakey

if [ -e $lockfile ]; then
echo -n "dropbear daemon is already running: "
success
echo
exit 0
fi

echo -n "Starting dropbear: "
daemon --pidfile="$pidfile" $dropbear -p $port -d $dsskey -r $rsakey
RETVAL=$?
echo

if [ $RETVAL -eq 0 ]; then
touch $lockfile
return 0
else
rm -f $lockfile $pidfile
return 1
fi
}

stop() {
if [ ! -e $lockfile ]; then
echo -n "dropbear service is stopped: "
success
echo
exit 1
fi

echo -n "Stopping dropbear daemon: "
killproc dropbear
RETVAL=$?
echo
if [ $RETVAL -eq 0 ]; then
rm -f $lockfile $pidfile
return 0
else
return 1
fi
}

status() {
if [ -e $lockfile ]; then
echo "dropbear is running..."
else
echo "dropbear is stopped..."
fi
}

usage() {
echo "Usage: dropbear {start|stop|restart|status|gendsskey|genrsakey}"
}
case $1 in
start)
start ;;
stop)
stop ;;
restart)
stop
start
;;
status)
status
;;
gendsskey)
gendsskey
;;
genrsakey)
genrsakey
;;
*)
usage
;;
esac
3配置文件位置/etc/sysconfig/dropbear
keysize=2048
port=22022
4後配置
chmod +x /etc/rc.d/init.d/dropbear
chkconfig -add dropbear

變量替換
變量替換可以根據變量的狀態(是否為空、是否定義等)來改變它的值
可以使用的變量替換形式:
形式 說明
${var} 變量本來的值
${var:-word} 如果變量 var 為空或已被刪除(unset),那麽返回?word,但不改變?var 的值。
${var:=word} 如果變量 var 為空或已被刪除(unset),那麽返回 word,並將 var 的值設置為 word。
${var:?message} 如果變量 var 為空或已被刪除(unset),那麽將消息 message 送到標準錯誤輸出,可以用來檢測變量 var 是否可以被正常賦值。若此替換出現在Shell腳本中,那麽腳本將停止運行。
${var:+word} 如果變量 var 被定義,那麽返回 word,但不改變 var 的值。

獲取字符串長度
string="abcd"
echo ${#string}#輸出 4
提取子字符串
string="alibaba is a great company"
echo ${string:1:4}#輸出liba
查找子字符串
string="alibaba is a great company"
echo expr index "$string" is

取得數組元素的個數

length=${#array_name[@]}

或者

length=${#array_name[*]}

取得數組單個元素的長度

lengthn=${#array_name[n]}
實例
#!/bin/bash
name[0]="Zadffrasdfsdaa"
name[1]="Qadsadfir"
name[2]="Mahnaasdsdfz"
name[3]="Aysdafsdan"
name[6]="Daiswwey"
name[7]="Daisery"
name[8]="Daisergy"
name[9]="Daaaisy"
echo "First Index: ${name[0]}"
echo "Second Index: ${name[1]}"
echo "${name[]}"
length=${#name[
]}
echo $length
lengthn=${#name[n]}
echo $lengthn

[root@www tmp]# ./5.sh
First Index: Zadffrasdfsdaa
Second Index: Qadsadfir
Zadffrasdfsdaa Qadsadfir Mahnaasdsdfz Aysdafsdan Daiswwey Daisery Daisergy Daaaisy
8
14 獲取的是屬組的第一個字符串的長度

顯示不換行
echo "OK!\c"
echo "It is a test"
輸出:
OK!It si a test

來看一個帶有return語句的函數:
函數返回值在調用該函數後通過 $? 來獲得
函數
#!/bin/bash
funWithReturn(){
echo "The function is to get the sum of two numbers..."
echo -n "Input first number: "
read aNum
echo -n "Input another number: "
read anotherNum
echo "The two numbers are $aNum and $anotherNum !"
return $(($aNum+$anotherNum))
}
funWithReturn

Capture value returnd by last command

ret=$?
echo "The sum of two numbers is $ret !"

[root@www tmp]# ./7.sh
The function is to get the sum of two numbers...
Input first number: 6
Input another number: 9
The two numbers are 6 and 9 !
The sum of two numbers is 15 !

再來看一個函數嵌套的例子:
#!/bin/bash

Calling one function from another

number_one () {
echo "Url_1 is http://see.xidian.edu.cn/cpp/shell/"
number_two
}
number_two () {
echo "Url_2 is http://see.xidian.edu.cn/cpp/u/xitong/"
}
number_one
運行結果:
Url_1 is http://see.xidian.edu.cn/cpp/shell/
Url_2 is http://see.xidian.edu.cn/cpp/u/xitong/

在Shell中,調用函數時可以向其傳遞參數。在函數體內部,通過 $n 的形式來獲取參數的值,例如,$1表示第一個參數,$2表示第二個參數...

帶參數的函數示例:
#!/bin/bash
funWithParam(){
echo "The value of the first parameter is $1 !"
echo "The value of the second parameter is $2 !"
echo "The value of the tenth parameter is $10 !"
echo "The value of the tenth parameter is ${10} !"
echo "The value of the eleventh parameter is ${11} !"
echo "The amount of the parameters is $# !"# 參數個數
echo "The string of the parameters is $* !"# 傳遞給函數的所有參數
}
funWithParam 1234567893473
運行腳本:
The value of the first parameter is 1 !
The value of the second parameter is 2 !
The value of the tenth parameter is 10 !
The value of the tenth parameter is 34 !
The value of the eleventh parameter is 73 !
The amount of the parameters is 12 !
The string of the parameters is 1 2 3 4 5 6 7 8 9 34 73 !"
註意,$10 不能獲取第十個參數,獲取第十個參數需要${10}。當n>=10時,需要使用${n}來獲取參數。

另外,還有幾個特殊變量用來處理參數,前面已經提到:
特殊變量 說明
$# 傳遞給函數的參數個數。
$ 顯示所有傳遞給函數的參數。
$@ 與$
相同,但是略有區別,請查看Shell特殊變量。
$? 函數的返回值。

像其他語言一樣,Shell 也可以包含外部腳本,將外部腳本的內容合並到當前腳本。

Shell 中包含腳本可以使用:
. filename

source filename
兩種方式的效果相同,簡單起見,一般使用點號(.),但是註意點號(.)和文件名中間有一空格。

例如,創建兩個腳本,一個是被調用腳本 subscript.sh,內容如下:
url="http://see.xidian.edu.cn/cpp/view/2738.html"
一個是主文件 main.sh,內容如下:
#!/bin/bash
../subscript.sh
echo $url
執行腳本:
$chomd +x main.sh
./main.sh
http://see.xidian.edu.cn/cpp/view/2738.html
$
註意:被包含腳本不需要有執行權限。

12、bash腳本變量總結