清空文件命令
清空文件的内容,使其变为空文件。
使用重定向符号 > 将空内容输出到文件,从而清空文件的内容。例:> example.txt
还可以使用:
- echo 命令:echo -n > example.txt 。其中,-n 参数用于防止 echo 命令输出末尾的换行符。
- truncate 命令。truncate 命令用于截断文件到指定大小。truncate -s 0 example.txt 可以用于清空文件内容
解压 zip
linux 文件最常用的是 unzip 命令。不过可能需要先安装
解压 gz
gunzip
解压 rar
When unrar throws the is not RAR archive error, it usually means one of two things: the file was corrupted during download/transfer, or it’s actually a different file type (like a .zip, .tar.gz, or .7z) that someone accidentally renamed to .rar.
You can use the file command to reveal its true identity:
bashfile mzzybak20260512.rar
Look closely at the output:
- If it says
Zip archive data, it's a ZIP file. - If it says
7-zip archive data, it's a 7-Zip file. - If it says
gzip compressed data, it's a tarball. - If it says
HTML documentorASCII text, the download failed and you likely downloaded a web page or an error message instead of the actual file.
Step 2: How to Extract It Based on the Result
Depending on what the file command tells you, use the matching command below to extract it (you don't even need to rename it back).
If it's a ZIP file:
bashsudo apt install unzip # if you don't have itunzip mzzybak20260512.rar
If it's a 7-Zip file:
bashsudo apt install p7zip-full # if you don't have it7z x mzzybak20260512.rar
If it's a GZIP/Tarball file:
bashtar -xvf mzzybak20260512.rar
复制文件
使用 cp 命令
| 用法 | 效果 |
|---|---|
| cp ./source ./dest | 将 source 目录复制到 dest 目录下,创建名为 source 的子目录。 |
| cp ./source* ./dest | 将 source 目录下的所有文件和子目录复制到 dest 目录下,不会创建名为 source 的子目录。 |
hosts file
- 编辑
/etc/hosts - flush DNS cache:
systemctl restart systemd-resolved
开机运行 shell 脚本
将脚本添加到 systemd 1启动项中,这适用于大多数现代 Linux 发行版2。
-
创建 systemd 服务文件:
sudo nano /etc/systemd/system/myscript.service -
在文件中添加以下内容并保存:
[Unit] Description=My Script Service After=network.target [Service] Type=simple ExecStart=/usr/local/bin/myscript.sh Restart=on-failure [Install] WantedBy=multi-user.target注意:这里的
ExecStart行指定了要运行的脚本的路径。 -
启用该服务:
bashsudo systemctl enable myscript.servicesudo systemctl start myscript.service
date
可以使用 date 命令来获取当前日期和时间
bash#!/bin/bash# 获取当前日期时间并存储在变量中datetime=$(date '+%Y-%m-%d %H:%M:%S')
在此示例中,date 命令使用格式字符串 '+%Y-%m-%d %H:%M:%S' 来获取当前日期和时间,该格式字符串将日期和时间格式化为 YYYY-MM-DD HH:MM:SS 的形式。
磁盘空间
使用 du 命令来查看某个文件夹占用的磁盘空间大小,常用的 du 命令选项:
- -h:以人类可读的格式显示磁盘空间大小。
- -s:仅显示总计大小,不显示子目录的大小。
- -c:同时显示所有目录的总计大小。 例如:
- du -h myfolder 查看当前目录下的 myfolder 文件夹占用的磁盘空间大小
- du -h -c myfolder 查看 myfolder 文件夹及其子目录的总计大小
按占用存储空间的大小降序排序
du 命令默认按照文件夹名称的字母顺序对结果进行排序。可以使用 -h 和 -s 选项配合 sort 命令来实现按占用存储空间的大小降序排序:du -sh * | sort -hr :
- -s 选项表示只显示每个目录的总大小。
- sort:排序命令;
- -h:按照“人类可读”的方式进行排序。即将数字单位转换为更大的单位(例如:1K 转换为 1024),再进行排序;
- -r:倒序排序。
程序输出追加到文件的新行
使用 >> 如 ls >> example.txt。如果文件不存在,则将创建一个新文件。如果文件已经存在,则输出将被追加到文件的末尾。
tree 命令打印目录结构
bashtree -L 2 -d -I node_modules .
后台运行脚本
nohup ./test > myout.txt 2>&1 &
使用了nohup命令,也使用了&符号,同时把标准输出/错误重定向到指定目录下。
使用了nohup之后,有可能在当前账户非正常退出或者结束的时候,命令还是自己结束了。所以在需要使用exit正常退出当前账户,才能保证命令一直在后台运行。
