目 录CONTENT

文章目录

Linux:nohup、&、 2>&1、/dev/null

gsh456
2025-01-17 / 0 评论 / 0 点赞 / 49 阅读 / 0 字

nohup

nohup(n ohang up)的意思是不挂起、永久执行
nohup运行命令可以使运行的命令永久的执行下去,和用户终端没有关系,可以在你退出帐户/关闭终端之后继续运行相应的进程。例如我们断开SSH连接并不会影响他的运行(注意:nohup没有后台运行的意思,&才是后台运行)

常用命令 nohup command &

nohup 输出

如果不将 nohup 命令的输出重定向,输出将附加到当前目录的 nohup.out 文件中。

如果当前目录的 nohup.out 文件不可写,输出重定向到 $HOME/nohup.out 文件中。

&

&是指在后台运行,当用户退出(挂起)、关闭终端的时候,后台运行的这条命令也会退出

/dev/null

/dev/null 表示空设备文件,是一个特殊的设备文件,它丢弃一切写入其中的数据,类似于黑洞(black hole)。

2>&1

2 表示错误输出(stdout),

1表示标准输出(stderr),

>是定向输出到文件,如果文件不存在,就创建文件;如果文件存在,就将其清空;

>> 这个是将输出内容追加到目标文件中。如果文件不存在,就创建文件;如果文件存在,则将新的内容追加到那个文件的末尾,该文件中的原有内容不受影响


所以2>&1连起来就是:将错误输出重定向到标准输出
为什么不写成2>1呢?在这里,2与>结合代表错误重定向,而1则代表错误重定向到一个文件1,而不代表标准输出,需要加上&

为了验证2>&1,可以做如下的测试
当前目录没有任何文件

$ls
total 0

ls 2>1
运行ls 2>1,不会报没有2文件的错误,会生成一个空的文件1

$ ls 2>1
1
$ ls
1

ls notExist 2>1
先删除上一次生成的文件1,运行ls notExist 2>1,没有notExist这个目录的错误输出到了1中

$ rm 1
$ ls notExist 2>1
$ cat 1
ls: notExist: No such file or directory1.2.3.4.

ls notExist 2>&1
先删除上一次生成的文件1,运行ls notExist 2>&1,屏幕直接输出了错误信息,没有生成文件1

$ rm 1
$ notExist 2>&1
ls: notExist: No such file or directory
$ ls
$1.2.3.4.5.

ls notExist >log.txt 2>&1
运行ls notExist >log.txt 2>&1, 生成了一个log.txt的文件, 并且错误输出打印到了文件里面

$ ls notExist >log.txt 2>&1
$ ls
log.txt
$ cat log.txt
ls: notExist: No such file or directory
$1.2.3.4.5.6.

> /dev/null 2>&1 和 2>&1 > /dev/null的区别

>/dev/null 2>&1: 标准输出和错误输出都被重定向到回收站(常用)
2>&1 > /dev/null: 错误输出到终端,标准输出被重定向到回收站

java常用

nohup java -jar javaFile.jar >/dev/null 2>&1 &

nohup java -jar javaFile.jar --spring.profiles.active=pro >/dev/null 2>&1 &

总结

所以,nohup command /dev/null 2>&1 &的意思就是,将command保持在后台运行,并且将输出的日志忽略

nohup 清空

通过不停服务清空nohup日志

cp /dev/null nohup.out

cat /dev/null > nohup.out

echo "" > nohup.out

0

评论区