Bash Shell备忘
Contents
Linux的Shell种类众多,常见的有:Bourne Shell(/usr/bin/sh或/bin/sh)、Bourne Again Shell(/bin/bash)、C Shell(/usr/bin/csh)、K Shell(/usr/bin/ksh)、Shell for Root(/sbin/sh)。其中Bash是大多数Linux系统默认的Shell, Bash Shell 脚本很简单,但是不常用的话,我这种记忆力能记住的实在有限,真要用到还得到处查手册。所以记个简单备忘,以便参考.
Hello World :)
|
|
字符串
字符串是shell编程中最常用最有用的数据类型(除了数字和字符串,也没啥其它类型好用了),字符串可以用单引号,也可以用双引号,也可以不用引号。单双引号的区别跟PHP类似。
- 单引号里的任何字符都会原样输出;单引号字符串中的变量是无效的;单引号字串中不能出现单引号(对单引号使用转义符后也不行)。
- 双引号里可以有变量;双引号里可以出现转义字符
- 拼接字符串
1 2 3 4your_name="qinjx" greeting="hello, "$your_name" !" greeting_1="hello, ${your_name} !" echo $greeting $greeting_1 - 获取字符串长度
1 2string="abcd" echo ${#string} #输出 4 - 提取子字符串
1 2string="alibaba is a great company" echo ${string:1:4} #输出liba - 查找子字符串
1 2string="alibaba is a great company" echo `expr index "$string" is`
数组
- 定义:
array_name=(value1 ... valuen) - 读取:
${array_name[index]} - 读取所有:
${array_name[*]},${array_name[@]} - 获取数组长度
1 2 3 4 5 6# 取得数组元素的个数 length=${#array_name[@]} # 或者 length=${#array_name[*]} # 取得数组单个元素的长度 lengthn=${#array_name[n]}
变量替换
${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 的值。
内置参数
$1,$2,$3, … are the positional parameters.$@is an array-like construct of all positional parameters, {$1,$2,$3…}.$*is the IFS expansion of all positional parameters,$1$2$3….$#is the number of positional parameters.$-current options set for the shell.$$pid of the current shell (not subshell).$_most recent parameter (or the abs path of the command to start the current shell immediately after startup).$IFSis the (input) field separator.$?is the most recent foreground pipeline exit status.$!is the PID of the most recent background command.$0is the name of the shell or shell script.
语句
if ... fiif ... else ... fiif ... elif ... else ... fiif test $[num1] -eq/-ne/-gt/-ge/-lt/-le $[num2]if test -e/-r/-w/-x/-s/-d/-f/-c/-b filename
Shell还提供了与( ! )、或( -o )、非( -a )三个逻辑操作符用于将测试条件连接起来,其优先级为:“!”最高,“-a”次之,“-o”最低。
case, for, while, until
其它
屏蔽 stdout 和 stderr
|
|
Author olOwOlo
LastMod 0001-01-01