Linux学习笔记——DAY2环境变量、脚本

学习资料:
shell十三问
linux命令行文本操作一文就够

1. 环境变量

(1)简单调用的方法(一次性)

#Method1:设置变量
$ bowtie2=/cluster/home/user/biosoft/bowtie2/bowtie2-2.4.1-linux-x86_64/bowtie2
cd
$ $bowtie2 #$表示变量
#Method2:设置alias
$ alias bowtie2=/cluster/home/user/biosoft/bowtie2/bowtie2-2.4.1-linux-x86_64/bowtie2
$ bowtie2
#Method3:添加环境变量
$ echo $PATH
$ export PATH="$PATH:/cluster/home/user/biosoft/bowtie2/bowtie2-2.4.1-linux-x86_64/"

以上为一次性的操作,要永久保留配置,需修改用户配置文件

(2)修改.bashrc文件(永久)

$ cat ~/.bashrc
$ cat >> ~/.bashrc#这里也可以用vim编译器进行操作
export PATH="$PATH:/cluster/home/yzhan/bin/bin"
$ source ~/.bashrc

2.脚本编程

(1) 变量及参数

$ vi temp.sh
echo $0 $1 ${10} ${11} #打印第0个参数及第1个参数,打印第10个参数及之后要加{}
$ bash temp.sh yys 0 1 2 3 4 5 6 7 8 9 x y z #运行脚本
temp.sh yys 8 9

命令替换符:反引号或$() 将命令的输出赋值给变量

testing='date'
testing=$(data) 注意${}是变量标识符,用于帮助bash shell 区分变量
echo $testing

(2) 通配符

*替代任意字符
[]中括号里字符任选一个,如[xy],在x,y中任选一个字符

(3) 脚本头文件

#!/bin/bash放脚本第一句

标明写脚本人信息的头文件

### --------------
###
### Create:yr
### Date:2020-03-31
### Email:
###
###---------------

(4) 循环语句

[user@lab test]$ ls *.rds | while read id; do echo $id; done
[user@lab test]$ for i in *rds; do echo $i; done
[user@lab test]$ for i in {1..20};do touch tmp${i}.txt;done #``是捕获的符号
[user@lab test]$ ls
tmp10.txt  tmp14.txt  tmp18.txt  tmp2.txt  tmp6.txt
tmp11.txt  tmp15.txt  tmp19.txt  tmp3.txt  tmp7.txt
tmp12.txt  tmp16.txt  tmp1.txt   tmp4.txt  tmp8.txt
tmp13.txt  tmp17.txt  tmp20.txt  tmp5.txt  tmp9.txt
[user@lab test]$for i in `ls *txt`; do echo $i; done 
tmp10.txt
tmp11.txt
tmp12.txt
tmp13.txt
tmp14.txt
tmp15.txt
tmp16.txt
tmp17.txt
tmp18.txt
tmp19.txt
tmp1.txt
tmp20.txt
tmp2.txt
tmp3.txt
tmp4.txt
tmp5.txt
tmp6.txt
tmp7.txt
tmp8.txt
tmp9.txt
[user@lab test1]$ ls /cluster/home/yzhan/temp/test/*txt|while read id; do ln -s $id $(basename $id);done#生成软链接

ln -s创建软链接
basename Print NAME with any leading directory components removed

(5) 输出捕获

1标准输出,2标准误输出

[yzhan@qlab temp]$ vim tmp.sh 
echo ffflklj
tmp
[yzhan@qlab temp]$ bash tmp.sh 
ffflklj
tmp.sh: line 2: tmp: command not found
[yzhan@qlab temp]$ bash tmp.sh 1>normal.txt 2>error.txt
[yzhan@qlab temp]$ cat normal.txt 
ffflklj
[yzhan@qlab temp]$ cat error.txt 
tmp.sh: line 2: tmp: command not found

(6) 输出重定向

command > outputfile 如果输出文件已经存在了,重定向操作符会用新的文件数据覆盖已有文件
command >> inputfile 用双大于号(>>)来追加数据,保留原数据。

(7) vim编译器

替换

#INSERT模式下进行操作
:s/old/new/g:一行命令替换所有old。
:n,ms/old/new/g:替换行号n和m之间所有old。
:%s/old/new/g:替换整个文件中的所有old。
:%s/old/new/gc:替换整个文件中的所有old,但在每次出现时提示。

(8)退出脚本

Linux提供了一个专门的变量$?来保存上个已执行命令的退出状态码。对于需要进行检查的命令,必须在其运行完毕后立刻查看或使用$?变量。它的值会变成由shell所执行的最后一条命令的退出状态码。

$ asdfg
-bash: asdfg: command not found
$ echo $?
127
$

0为正常退出;126命令不可执行;127没找到命令。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容