强引用 ’ ’ 单引号:将字符串放置在单引号中,保留字符串中所有字符的文字值,同时禁用所有扩展. 弱引用 ” ” 双引号:将字符串放置在双引号中,变量扩展和命令扩展在双引号内仍起作用. 转义 \ 反斜线:非引用的\是转义字符.它保留了下一个字符的文字值.
shell变量用于为稍后在脚本中使用的名称指定值,并且仅限于shell命令行或从中声明变量的脚本,常用大写表示.使用时变量前加$. 例子:
#!/bin/bash NAME=yang echo name is $NAMEfor语句
for N in $(seq 1 2 10 ) ##1-10间隔为2 do echo "$N" done 用(())表示数学运算. #!/bin/bash for ((i=1;i<10;i++)) do ((j+=i)) done echo $jif语句
#!/bin/bash if [ 1 > 0 ] then echo 1 else echo 0 fi [root@server mnt]# sh shell.sh 1case语句
#!/bin/bash case "$1" in 1) echo This is 1 ;; 2) echo This is 2 ;; *) echo NOT 1 OR 2 ;; esac [root@server mnt]# sh shell.sh 1 This is 1 [root@server mnt]# sh shell.sh 12 NOT 1 OR 2 [root@server mnt]# sh shell.sh 2 This is 2read提示用户输入(使用-p选项)并将其直接存储到一个或多个变量
#!/bin/bash read -p "please input:" WORD echo word is $WORD [root@server mnt]# sh shell.sh 2 please input:yang word is yang使用位置参数来读取传递给脚本的命令行参数或选项输入。各种特殊变量存储传递的选项编号
指定的位置参数总数:$# 位置参数自身:$0、$1、$2、$3.... 所有位置参数: $@、$*yum install expect.x86_64 -y ##自动应答脚本所需软件 vim /mnt/ssh
read -p "please user" -s USER read -p "please IP" -s IP ssh ${USER}@${IP}vim /mnt/answer.exp
#!/usr/bin/expect set USER [ lindex $argv 0 ] set PASSWD [ lindex $argv 1 ] set IP [ lindex $argv 2 ] spawn /mnt/ssh expect { "please user" { send "$USER\r"; exp_continue } "yes" { send "yes"; exp_continue } "please IP" { send "$IP\r"; exp_continue } "password" { send "$PASSWD\r"; exp_continue } expect eof } [root@server mnt]# /mnt/answer.exp root westos 172.25.254.62 spawn /mnt/ssh please userplease IProot@172.25.254.62's password: Last login: Thu Mar 9 16:54:56 2017 from 172.25.254.10 [root@yang ~]#shell和脚本使用变量来存储数据 ,有些变量可以连同它们的内容传递给子进程,这些变量我们称之为环境变量. export ##环境级 vim ~/.bash_profile ; source .bash_profile ##用户级 vim /etc/profile ; source /etc/profile ##系统级