1

Linux | Bash 基础

 2 years ago
source link: https://ijayer.github.io/post/tech/os/linux/20170515-bash-basic-notes/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

一个工具·bash-completion

选项/参数补齐

$ apt install bash-completion

Bash中的常用命令

type

# 查询指令是否为bash shell的内置指令(找指令)

echo

# 变量的取用与设置
$ $Variable_Name | ${Variable}
# 设置myname变量:
$ myname=zhe

printf

# Usage
$ printf format-string [args...]
$ printf "%d %s\n" 1 "abc"

test

# test命令用于测试某个条件是否成立
# 测试对象: 数值,字符串,文件
# [] 也是用于测试某个条件是否成立的,等价于 test 指令

unset

# 取消设置的变量
$ unset myname

反单引号

# 反单引号包含的命令会优先执行,结果作为外部的输入  

env

# 列出目前shell中所有的环境变量

set

# 列出系统所有变量(环境变量 & 自定义变量)

$

# 目前shell的pid
# 本身就是一个变量

?

# 上个执行指令的回传值:0-正确,!0-错误
# 本身就是一个变量

export

# 自定义变量转化成环境变量
# 自定义变量不能被子程序bash继承

locale

# 影响显示结果的语系变量(解决乱码)

read

# 读取键盘输入的变量
# -p:后面接提示信息
# -t:后面接等待的秒数
$ read -p "Please keyin your name: " -t 30 myname
$ echo $myname

declare/typeset

# 宣告变量的类型
# Options: [-aixr]

ulimit

# 与文件系统及程序的限制关系
$ ulimit [-SHacdfltu] [配额]

alias & unalias

# 命令的别名与取消命令的别名
$ alias 别名='指令 选项...'

history

# Bash命令历史 | 别名如下
$ alias h='history'`
$ !n` 执行第 n 条命令
$ !!` 执行上一条命令
$ !command` 执行最近的以'command'开头的指令

Bash Shell操作环境

命令执行顺序

# 路径下搜索( 绝对 /bin/ls | 相对 ./ls )
# alias
# builtin
# $PATH 中的第一个

Bash的环境配置文件

login shell

  • 取得bash时需要完整的登陆流程

  • login shell读取的配置文件

    • /etc/profile:整个系统的设置(login shell才会读)

      注:/etc/profile 还会调用外部的配置文件数据, 如下

      • /etc/profile.d/*.sh
      • /etc/locale.conf
      • /usr/share/bash-completion/completions/*
    • ~/.bash_profile~/.bash_login~/.profile:用户自定义的设置(login shell才会读)

      注:以上用户配置文件只会读其中一个
      + ~/.profile最终会读取 ~/.bashrc

    • login shell 的配置文件读取流程

non-login shell

  • 取得bash接口的方法不需要重复操作
  • non-login shell读取的配置文件

    • ~/.bashrc

* 代表 “0 到无穷多个” 任意字符
? 代表 “一定有一个” 任意字符
[] 代表 “一定有一个在括号内” 的字符(非任意字符)

数据流重导向

  • stdin:代码为0, <<<

    • 将原本由键盘输入的数据改由从文件获取
  • stdout:代码为1, >>>

  • stderr:代码为2, 2>2>>

  • > & 2> 覆盖

  • >> & 2>> 累加

命令执行的判断依据

  • ; 不考虑指令相关性的连续下达
  • &&
  • ||
  • $? 上个指令的回传值

管道 Pipe

  • | 管道界定符

    • 把上个命令的输出(stdout)作为下一个命令的输入(stdin),会忽略掉stderr的输出
  • grep (Global Regular Expression Print)

    • 查找文件中符合条件的字符串

    • grep [-acinv] 'search_str' filename

    • Options

      • -a 将binary文件以text文件方式搜索数据
      • -c 统计找到的 ‘search_str’ 的次数
      • -i 忽略大小写
      • -n 输出行号
      • -v 反向选择,即显示没有 ‘search_str’ 的哪一行
  • - 减号

    • 可以代替 stdin 和 stdout

See Also

Thanks to the authors 🙂


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK