前端analysis | 3w & 1h

《Linux》- shell脚本逻辑控制编写

2020-05-06

shell 文件权限

shell 开头

  • 以sh后缀
  • 开头#注释,表明采用何种解释器
    1
    #!/bin/bash 
  • 添加作者等说明
    1
    2
    3
    4
    5
    6
     #/bin/bash
    <<ABC
    author:cheonghu
    date:2020-05-06
    desc:shell demo
    ABC

文件权限

1
2
3
$ ll 
total 4
-rw-r--r-- 1 root root 88 Apr 24 22:15 demo.sh
  • 其中可以看到,demo.sh没有可执行权限;但是 bash demo.sh可以运行
    1
    2
    3
    4
    5
    $ ./demo.sh
    -bash: ./demo.sh: Permission denied

    $ bash ./demo.sh
    shell demo
  • 也可以通过chmod 修改权限
    1
    2
    3
    4
    5
    $ chmod 755 ./demo.sh 
    # or
    $ chmod u+x ./demo.sh # 给当前拥有者添加可执行权限
    $ ll
    -rwxr--r-- 1 root root 88 Apr 24 22:15 demo.sh

shell 代码执行

shell - A;B 依次执行

1
2
3
4
# 两条命令,按照前后顺序执行
$ echo 'hello '; echo 'world'
hello
world

shell - A && B 有前提条件的执行

1
2
3
4
# 前一条命令,执行成功,才继续执行下一条
$ echo 'hello ' && echo 'world'
hello
world

shell - A || B 兜底策略的执行

1
2
3
# 前一条执行不成功,才执行下一条
$ echo 'hello ' || echo 'world'
hello

shell 代码运算

$()

1
2
$ echo $(2+5)
-bash: 2+5: command not found

$(())

1
2
$ echo $((2+5))
7

$[]

1
2
$ echo $[2+5]
7

仅支持的运算符内容,其他无效

  • ++, - -
  • +,-,*,/
  • **, %, ?:(三目运算符)
  • +=,-=,*=,/=,%=
  • &&, ||
  • <, <=, >,>=

let

1
2
3
$ let x=4,y=5;
$ echo $x
$ echo $[x+y]

bash不支持小数计算、let定义变量

1
2
3
4
5
6
7
8
9
10
11
12
$ let x=2.2 
-bash: let: x=2.2: syntax error: invalid arithmetic operator (error token is ".2")
$ bc
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.

let x=2.2
(standard_in) 8: syntax error
1.5+3.2
4.7

echo中引用bc

1
2
3
4
5
6
$ x=$(echo "scale=4;(49+6-30+10)/9;" | bc)
3.8888
# 错误做法
$ x=$[echo "scale=4;(49+6-30+10)/9;" | bc]
-bash: echo "scale=4;(49+6-30+10)/9;" | bc:
syntax error: invalid arithmetic operator (error token is ""scale=4;(49+6-30+10)/9;" | bc")
1
2
3
# 1000以二进制的形式输入
$ echo "ibase=2;1000" | bc
8
1
2
3
# 8以2进制形式输出
$ echo "obase=2;8"|bc
1000
使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏