前端analysis | 3w & 1h

《Linux》- shell脚本输入|输出|管道

2020-04-24

shell 编写

shell 开头

  • 以sh后缀
  • 开头#注释,表明采用何种解释器
    1
    #!/bin/bash 
  • 添加作者等说明
    1
    2
    3
    4
    5
    6
     #/bin/bash
    <<ABC
    author:cheonghu
    date:2020-04-24
    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 输出 - echo

  • 输出特殊字符
    1
    2
    3
    $ echo -e "hello\tworld"
    $ echo -e "hello\nworld"
    $ echo -e "hello\fworld"
  • 输出待颜色字符串
    1
    2
    3
    # \e[35m开启,\e[0m关闭 
    $ echo -e "\e[35mok\e[0m"
    $ echo -e "\e[32mOK\e[0m"

shell 输出 - printf

1
2
$ printf "%5d" 12 # 十进制右对齐输出,但是默认不换行
$ printf "%-5d" 12 # 十进制左对齐输出

shell 输入 - read

1
2
3
4
5
6
7
8
9
10
11
12
13
$ read name  #把输入的值,赋值给name
$ echo $name

$ read name age address # 读入3组
$ echo $name $age $address

$ read -p "请输入用户名" user
$ echo $user

$ read -t -10 -p "请输入用户名" user # 3s后自动退出等待输入状态
$ echo $user

$ read -s -p "请输入密码" pass # 不显示方式输入密码

shell - 管道 |

  • who查看最近登录用户
  • wc 统计输入数据的行数-l,单词数 -w, 字节-c,字符-m
    1
    $ who | wc -l
  • ss 可查看系统服务监听的端口,grep 具备过滤功能
    1
    $ ss -nutlp | grep sshd
使用支付宝打赏
使用微信打赏

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