linux shell的一些琐事

2018-06-27  本文已影响0人  山有木紫

/dev/null

参考资料
把/dev/null看作"黑洞"。它等价于一个只写文件,并且所有写入它的内容都会永远丢失,而尝试从它那儿读取内容则什么也读不到。

当目录中的文件test.log 存在的时候,使用"cat test.log",则会将test.log中的内容输出到标准输出上,而使用"cat test.log > /dev/null"则没有任何内容输出到标准输出上。

如果test.txt文件不存在时,使用"cat test.txt"命令时,会输出"cat: test.txt: No such file or directory",解决这个问题不是"cat test.txt >/dev/null",而是需要"cat test.txt 2>/dev/null",将标准错误( 2 )输出重定向到/dev/null。
/dev/null
同时禁止标准输出和标准错误的输出:

cat filename 2>/dev/null >/dev/null

所以:

或者用cat test.txt 2>/dev/null 2>&1
2>&1的意思是:
0,1,2 分别代表stdin stdout 和stderr
2>&1 redirects standard error (2) to standard output (1)

在bash中使用颜色

参考资料

command -v

$ command -v python
/usr/bin/python

用来显示命令的路径,也可以用来判断命令是否存在

bashrc文件

bashrc文件默认位置在~/.bashrc用来设置一些环境变量
最好给它赋予初值

# User specific aliases and functions
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'

# Source global definitions
if [ -f /etc/bashrc ]; then
        . /etc/bashrc
fi

前者会在删除和文件覆盖的时候予以提示
后者会把全局的设置用在本用户上

设置环境变量

PATH=$PATH:/home/christine/Scripts

最好是在/etc/profile.d目录中创建一个以.sh结尾的文件。把所有新的或修改过的全局环境变量设置放在这个文件中。

让文件夹下所有文件归属所有的组

groups命令可以查看用户在哪些组中
usermod -G shared qiyuhao

usermod -a -G shared qiyuhao # 把qiyuhao加到shared组中,-a是append的意思
chgrp shared testdir # 改变testdir所属的组
chmod g+s testdir # 让testdir下所有的文件归属同样的组

条件语句

if-then 语句

如果该命令的退出状态码是0 (该命令成功运行),位于then部分的命令就会被执行。如果该命令的退出状态码是其他值, then部分的命令就不会被执行,bash shell会继续执行脚本中的下一个命令。fi语句用来表示if-then 语句到此结束

if command1 
then
  command set 1
elif command2 
then
  command set 2
elif command3 
then
  command set 3
elif command4 
then
  command set 4 
fi

test 命令

if test condition 
then
  commands 
fi

bash shell提供了另一种条件测试方法,无需在if-then语句中声明test命令。

if [ condition ] 
then
  commands 
fi

注意:bash shell只能处理整数,不能用浮点数

case variable in
pattern1 | pattern2) commands1;; 
pattern3) commands2;; 
*) default commands;; 
esac

循环语句

for

for var in list 
do
    commands
done

这里的var在循环语句结束之后也会保持其值
for命令用空格来划分列表中的每个值

上一篇下一篇

猜你喜欢

热点阅读