查看本机支持的shell
[root@VM_0_2_centos /]# cat /etc/shells
/bin/sh
/bin/bash
/sbin/nologin
/usr/bin/sh
/usr/bin/bash
/usr/sbin/nologin
/bin/tcsh
/bin/csh
变量的定义
a=1
b=hello
c="hello world"
d='"hello world" 你好'
e=`ls`
[[email protected] ~]$ a="hello testerhome"
[[email protected] ~]$ echo "$a"
hello testerhome
[[email protected] ~]$ echo '$a'
$a
echo $a
echo ${a}
echo “$a”
使用$var 或 ${var}来访问变量,后者更严谨
变量不需要定义也可以使用,引用没定义的变量,默认为控制
[~]$ echo $PWD
/home/21146916
[~]$ echo $HOME
/home/21146916
[~]$ echo $USER
21146916
[~]$ echo $PATH
/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/21146916/.local/bin:/home/21146916/bin:/home/21146916/test
使用()来定义数组变量,中间使用空格隔开
array=(1 2 3 4)
array=`ls`
# 打印第一个元素
array=(1 2 3 4 5)
echo ${array[0]}
1
# 打印所有元素
echo ${array[*]}
1 2 3 4 5
# 打印数组长度
echo ${#array[*]}
5
[~]$ array=`ls`
[~]$ echo ${array}
2.txt a baidu.html baidu.txt file1.txt lbtest leetcode nginx.log rand.sh test testerhome.sh testfunc1.sh testfunc2.sh test_func.sh testfunc.sh test_script.sh test.txt
[~]$ a="hello world"
[~]$ echo $a
hello world
[~]$ a="hello world"
[[email protected] ~]$ echo "$a"
hello world
[[email protected] ~]$ echo '$a'
$a
[root@VM_0_2_centos /]# echo $(ls)
bin boot data dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var
[root@VM_0_2_centos /]# echo `ls`
bin boot data dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var
[root@VM_0_2_centos /]# echo $((2+3))
5
[root@VM_0_2_centos /]# a=1
[root@VM_0_2_centos /]# b=3
[root@VM_0_2_centos /]# echo $((a+b))
4
[root@VM_0_2_centos /]# ((a=2+3))
[root@VM_0_2_centos /]# echo $a
5
[root@VM_0_2_centos /]# a=({1..10})
[root@VM_0_2_centos /]# echo ${a[*]}
1 2 3 4 5 6 7 8 9 10
[root@VM_0_2_centos /]# echo ${a[@]}
1 2 3 4 5 6 7 8 9 10
[root@VM_0_2_centos /]# seq 10
1
2
3
4
5
6
7
8
9
10
# 字符串型
a="hello world"
# 数字型
b=1314
# 布尔型
c=true d=false
整数计算
[root@VM_0_2_centos /]# a=10
[root@VM_0_2_centos /]# echo $((a+10))
20
[root@VM_0_2_centos /]# echo $((a-10))
0
[root@VM_0_2_centos /]# echo $((a*10))
100
[root@VM_0_2_centos /]# echo $((a/10))
1
浮点数计算请使用awk "BEGIN{print 1/3}"
[root@VM_0_2_centos /]# awk "BEGIN{print 3/5}"
0.6
[root@VM_0_2_centos /]# echo $((3/5))
0
[root@VM_0_2_centos /]# var="hello world"
[root@VM_0_2_centos /]# echo ${var:2}
llo world
[root@VM_0_2_centos /]# var="hello world"
[root@VM_0_2_centos /]# echo ${var/world/python}
hello python
# 全局替换
[root@VM_0_2_centos /]# var="hello world world"
[root@VM_0_2_centos /]# echo ${var//world/python}
hello python python
[root@VM_0_2_centos /]# ls |echo $?
0
算术判断
[root@VM_0_2_centos home]# [ 2 -eq 3 ];echo $?
1
[root@VM_0_2_centos home]# [ 2 -eq 2 ];echo $?
0
[root@VM_0_2_centos home]# [ 2 -ne 2 ];echo $?
1
[root@VM_0_2_centos home]# [ 2 -ne 3 ];echo $?
0
[root@VM_0_2_centos home]# [ "a" == "a" ];echo $?
0
[root@VM_0_2_centos home]# [ "a" == "b" ];echo $?
1
[root@VM_0_2_centos home]# [ -n "" ];echo $?
1
[root@VM_0_2_centos home]# [ -n ];echo $?
0