1. Bash及shell基本知识
默认使用b_shell(使用type)
shell含义
shell可以将输入的命令和内核沟通,以便让内核控制硬件工作。
在linux中,shell主要分为b_shell 和c_shell。Bash即是b_shell的一种(全称Bourne Again Shell)
bash环境配置文件
系统存在一些环境配置文件,Bash在启动时会直接读取这些文件。
这些文件分为全局系统配置文件和用户个人偏好配置文件
/etc/profile:全局系统配置文件。该文件可利用用户标识符来决定很多重要的变量数据,最好不要修改
~/.bash_profile:个人偏好配置文件。调用.bashrc文件;在PATH变量后面加入了“:$HOME/bin”这个目录
login和non-login shell
两种登录方式取得bash的情况中,都会自动读取配置文件,但是二者读取的文件并不一样。一般来说,login shell只会读取 /etc/profile 和 ~/.bash_profile或~/.bash_login或~/.profile(三个文件按读取优先级排列)两个配置文件;non-login shell只会读取~/.bashrc
进程管理
在当前shell下去启动另一个新shell,新shell就是子进程,当前shell就是父进程。只有当exit退出子进程时才会回到父进程。
2. 命令行模式
变量
通常大写字符为系统默认变量,自行设置变量可以用小写
子进程会继承父进程的环境变量,但不会继承其自定义变量。
echo $username //查看变量
username=/var/spool/mail/user //设置变量:等号两边不能有空格
var=”where is $username” //双引号内的特殊字符可以保留原特性,echo结果:where is /var/spool/mail/user
//单引号内的仅是纯文本
export username //父进程的自定义变量是无法在子进程中使用,可通过export将变量变成环境变量
env //查看环境变量,等同于export;set可查看所有变量(环境变量+自定义变量)
unset:username //取消变量
命令别名
类似于宏定义
alias cls=‘clear’
3 脚本模式
Create a file and write info to it
set SRC “I have an English name.”
set file_wr_id [open data.txt w+]
puts $file_wr_id $SRC #将变量写进文件
flush $file_wr_id #刷新
close $file_wr_id #与flush成对使用
#Read sth from a file
set DST “”
set file_rd_id [open data.txt r]
set $file_rd_id DST
echo “Read from the file: {$DST}”
close $file_rd_id
子程序
proc max {a, b} {
if {$a > $b} {
set y $a;
}else{
set y $b;
}
return $y;
}
循环语句
while {$i < 10}{
echo “Current value of i is $i”;
incr i 1 #自增1
}
for{set idx 0} {$idx < 10}{incr idx 1} {
if{$idx == 8} {
continue; #当idx等于8时,下面的语句直接跳过不运行
}
echo “Current value of idx is $idx”;
}
foreach NAME $NAMES{
echo “$NAME is here!”
}
条件语句
if{var == 1}{
}elseif{var == 2}{
}else{
}
switch -regexp -exact $NAME {
“kevin” {
echo “It’s my name.”;
}
“lisa” {
echo “It is not my name.”;
}
default {
echo “It’s a secret.”
}
}
本文分享 CSDN – KGback。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。