变量名=值, (注意。= 两边不能有空格)
var=1
var=$var+1
echo $var+1
输出为1+1,而不是2
能够用例如以下方法使其输出为2
let "var+=1"
#var=$[$var+1]
#var=$(($var+1))
echo $var
或者
var=1
var= expr $var + 1 #(注意,+ 两边的空格,一定要有)
let表示数学运算,expr用于整数值运算。每一项用空格隔开,$[]将中括号内的表达式作为数学运算先计算结果再输出。
在bash中。将数学运算结果赋给某个变量。 var=$[ operation ]
变量自增,自减
let var++ let var--
let var+=2
echo "10.2-2" | bc -- 小数运算要用bc $[]不支持小数
$var ${var} " " 中能够用$var ,\" ‘ ‘ 中不能够用$var \" $(cmd) 与 `cmd` 等效
内建变量
条件变量替换
Bash Shell能够进行变量的条件替换,既仅仅有某种条件发生时才进行替换,替换条件放在{}中.
message}
?若变量已赋值的话,正常替换.否则将消息message送到标准错误输出若此替换出如今Shell程序中,那么该程序将终止执行.-e filename 假设 filename 存在,则为真 [ -e /var/log/syslog ]
-d filename 假设 filename 为文件夹。则为真 [ -d /tmp/mydir ]
-f filename 假设 filename 为常规文件,则为真 [ -f /usr/bin/grep ]
-L filename 假设 filename 为符号链接,则为真 [ -L /usr/bin/grep ]
-r filename 假设 filename 可读,则为真 [ -r /var/log/syslog ]
-w filename 假设 filename 可写。则为真 [ -w /var/mytmp.txt ]
-x filename 假设 filename 可执行。则为真 [ -L /usr/bin/grep ]
filename1 -nt filename2 假设 filename1 比 filename2 新。则为真 [ /tmp/install/etc/services -nt /etc/services ]
filename1 -ot filename2 假设 filename1 比 filename2 旧。则为真 [ /boot/bzImage -ot arch/i386/boot/bzImage ]
-z string 假设 string 长度为零,则为真 [ -z "$myvar" ]
-n string 假设 string 长度非零,则为真 [ -n "$myvar" ]
string1 = string2 假设 string1 与 string2 同样,则为真 [ "$myvar" = "one two three" ]
string1 != string2 假设 string1 与 string2 不同。则为真 [ "$myvar" != "one two three" ]
num1 -eq num2 等于 [ 3 -eq $mynum ]
num1 -ne num2 不等于 [ 3 -ne $mynum ]
num1 -lt num2 小于 [ 3 -lt $mynum ]
num1 -le num2 小于或等于 [ 3 -le $mynum ]
num1 -gt num2 大于 [ 3 -gt $mynum ]
num1 -ge num2 大于或等于 [ 3 -ge $mynum ]
if command
then
commands
fi
if command; then #假设then与if在同一行,if command后要加‘;‘
commands
fi
if command
then
commands
else
commands
fi
if command1
then
commands
elif command2
then
commands
fi
if test condition
if [ condition ] 注意[]与condition之间的空格。> < 须要转义
then
commands
fi
if ((expression)) > < 不须要转义
then
commands
fi
if [[condition]] 能够用正則表達式
then
commands
fi
case variable in
pattern1 | pattern2)
commands1
;;
pattern3)
commands2::
;;
*)
default commands
;;
esac
for var in list
do
commands
done
while test command
do
other commands
done
until test command
do
other commands
done
break n (default 1) 跳出n层循环
continue n (default 1) 继续n级循环
select var in list
do
commands
done
语法
[ function ] funname [()]
{
action;
[return int;]
}
说明:
1. 能够带function fun() 定义。也能够直接fun() 定义,不带不论什么參数。
2. 參数返回,能够显式return返回,return后跟数值n(0-255)。假设不加,将以最后一条命令执行结果。作为返回值。
注意事项
不会像其他语言一样先预编译。一次必须在使用函数前先声明函数。
因此,我们能够将shell中函数。看作是定义一个新的命令。它是命令,因此 各个输入參数直接用 空格分隔。 一次。命令里面获得參数方法能够通过:$0…$n得到。 $0代表函数本身。
export PS4=‘+${BASH_SOURCE}:${LINENO}:${FUNCNAME[0]}:
‘
_log() {
if [ "$_DEBUG" == "true" ]; then
echo 1>&2 "$@"
fi
}
能够在脚本中调用 _log "log msg"
假设不设置_DEBUG=true, LOG信息就不会打印出来
路径切割?dirname 获取文件夹 basename 获取文件名称
生成数字序列?seq start end seq start offset end
字符串截取
${}: ${var:起始位置:截取长度} 起始位置从0開始,建议用这样的
字符串替换?${var/old/new} 替换第一个匹配的old为new ${var//old/new} 替换全部匹配的old为new
原文:https://www.cnblogs.com/ldxsuanfa/p/10504950.html