20 条可添加到你的工具箱中的单行 Linux 命令
许多 Linux 用户在编写出一条特别巧妙的命令后,都体验到了持久的成就感,该命令仅用一行即可实现多项操作,或者在一行中完成通常需要单击 10 次并在图形用户界面 (GUI) 中打开多个窗口才能完成的操作。除了成为传奇之外,单行命令还是终端被视为如此强大工具的绝佳例子。
读完本文后,你将获得:
- 20 条命令列表可让你在 Linux 上工作时更轻松
- 了解将简单命令组合起来以创建更强大的命令的可能性
- 运行这些命令比你想象的更有趣
这些是我们为 Linux 终端挑选出的 20 条单行命令(无先后顺序)。虽然我们用符号将一些较长的命令分开,\
以便于阅读,但您可以在终端的一行中输入它们,因为它们毕竟是单行命令。
1. 对不同名称的文件应用命令
shell{}
运算符非常适合此操作。以下是包含三个目录的示例{}
:
$ mkdir -p -v /home/josevnz/tmp/{dir1,anotherdir,similardir}
2. 现场编辑文件
您是否想在不使用编辑器的情况下替换一个或多个文件中的字符串?当然,sed
这里有解决方案:
$ sed -i 's#ORIGINAL_VALLUE#NEW_VALUE#g' myfile1 myfile2
但是等等,Perl 爱好者会告诉你他们也可以做同样的事情:
$ perl -p -i -e 's#ORIGINAL#NEW_VALUE#' myfile1 myfile2
3. 使用 Web 服务器快速共享文件
如果你还没有使用过这个功能至少一次来快速共享目录,请举手:
$ cd $mydir && python3 -m http.server 8888
4. 使用 journalctl 查找故障
journalctl
有时会出现问题。您可以使用以及经典工具sort
和的组合来查找最新的错误uniq
:
$ journalctl --no-pager --since today \
--grep 'fail|error|fatal' --output json|jq '._EXE' | \
sort | uniq -c | sort --numeric --reverse --key 1
898172 "/usr/bin/dockerd"
752 "/usr/local/sbin/node_exporter"
30 "/usr/bin/gnome-shell"
26 "/usr/bin/cat"
22 "/usr/libexec/gsd-media-keys"
[...]
在这种情况下,Docker 守护进程似乎不高兴。
[下载此电子书,为 Red Hat 远程考试做好准备。]
5. 通过加密文件传输进行备份
使用ssh
和tar
进行安全备份。它们就像花生酱和果冻一样密不可分:
$ tar --create --directory /home/josevnz/tmp/ --file - *| \
ssh raspberrypi "tar --directory /home/josevnz \
--verbose --list --file -"
您可以使用压缩和加密为备份工作增添风味——就像在三明治中添加配料一样。
6. 写入即时文件
当你需要编写多行文档时,这是一个很好的技巧:
$ cat<<DOC>/my/new/file
Line1
Line2
A $VARIABLE
DOC
您也可以cat > file
直接输入 EOF 字符(Ctrl+D):
[josevnz@dmaf5 temp]$ cat > testfile
This is a test
multiple lines
and here we go
[josevnz@dmaf5 temp]$
7. 搜索文件,包括某些扩展名并排除其他扩展名
本例使用grep
搜索特定文件的方式,这种方式非常快捷且容易记住:
$ grep -R 'import' --include='*.java' --color MySourceCodeDir
或者你可以尝试以下find
方式(用于xargs
正确处理大量匹配):
$ find MySourceCodeDir/ -name '*.java' -type f -print| xargs \
grep --color 'import
你可能会问,为什么find
?你可以结合使用,find
先-exec
对文件执行操作,然后将结果传递给过滤器。这里的处理可能性无穷无尽。
8. Monitor memory without top or htop
This one is almost cheating. It repeats a command, such as free
, every five seconds and highlights the differences:
$ watch -n 5 -d '/bin/free -m'
9. Display disk partition sizes
Use lsbk
(list block) and jq
(to manipulate a JSON on the command line) to display partition information:
$ lsblk --json | jq -c '.blockdevices[]|[.name,.size]'
["loop0","55.5M"]
["loop1","156M"]
["loop2","32.3M"]
["zram0","4G"]
["nvme0n1","476.9G"]
10. Quickly display a file type
The What is function is called with wi
. It quickly tells you a file's type.
To check a single file:
$ function wi { test -n "$1" && stat --printf "%F\n" "$1"; }
To check multiple files:
$ function wi { test "$#" -gt 0 && stat --printf "%n: %F\n" "$@"; }
NOTE: Functions are superior and can do the same work as an alias.
11. Display the size of an installed RPM
If you have an RPM-based system, sooner or later, you will format your queries. Here's an example:
$ rpm --queryformat='%12{SIZE} %{NAME}\n' \
-q java-11-openjdk-headless
12. Display the total size of a group of files
In this case, the find
command acts as a filter, displays the size of each file in bytes, and finally, shows the total size:
$ t=0; for n in $(find ~/Documents -type f -name '*.py' -print | xargs \
stat --printf "%s "); do ((t+=n)); done; echo $t
Or, if you want a function (better), try this approach:
$ function size { t=0; test -d "$1" && for n in $(find $1 \
-type f -name '*.py' -print| \
xargs stat --printf "%s "); do ((t+=n)); done; echo $t; }
size $mydir
13. Update all Git repositories on a directory
You already know how useful Git is. Here's a trick to be more efficient with your updates:
$ for i in */.git; do cd $(dirname $i); git pull; cd ..; done
14. Expose a web directory using containers
Containers are critical today. This one-liner exposes a directory via Podman:
$ podman run --rm -v .:/usr/share/nginx/html:ro,Z \
-p 30080:80 -d nginx
15. Check the weather
Use this function to find out whether you need a jacket today:
weather() { curl -s --connect-timeout 3 -m 5 http://wttr.in/$1; }
16. Display the top 10 IP addresses hitting a webserver
Here's a task web admins may use frequently with Nginx (it may also work with Apache) to grab the top 10 internet protocol addresses hitting a webserver from the access log:
$ cat /var/log/nginx/access.log | cut -f 1 -d ' ' | sort | \
uniq -c | sort -hr | head -n 10
17. Round floats in Bash with Python's help
You can do pretty cool stuff with Python, but this example just rounds numbers:
$ echo "22.67892" | python3 -c "print(f'{round(float(input()))}')"
23
18. Run a mini calculator
This function defines a quick calculator on the command line with variable precision (the default is 2). It uses bc. Create the function like this:
$ function qqbc() { echo "scale=${2:-2}; $1" | bc -l
Next, perform a quick calculation:
$ qqbc "2/3"
.66
In case you need additional precision, just define a second parameter:
$ qqbc "2/3" 4
.6666
This tool is called qqbc
because it's an improvement on the old function qbc
.
19. Convert a CSV to JSON
This trick is a modification of this popular recipe to convert CSV files to the JSON format:
$ python3 -c \
"import csv,json,sys;print(json.dumps(list(csv.reader(open(sys.argv[1])))))" \
covid19-vaccinations-town-age-grp.csv
20. Install and run commands with Docker
If you have Docker installed and you want to run a command without installing a bunch of dependencies on your system (while doing a quick run), this may be all you need:
$ docker run --rm --interactive curlimages/curl curl \
--verbose --location --fail --silent --output - \
https://example.com
The command runs the latest version of curl
from a container, and later removes it. Notice that the command ends with a dash (-
), which tells curl
to output to your terminal. The possibilities are endless here.
Wrap up
The ability to build powerful combinations of simple commands is one of the reasons Unix and Linux are so popular.
Fortunately. it is not difficult to learn these one-liners. Focus on remembering what a simple command does, and then think about how you can mix many simple commands to make a powerful recipe.
Always check the man
page or use the info
command to figure out what else the tool can do. You may be surprised to learn that one tool can do everything without combining it with another utility.
There are many sites on the internet with plenty of one-line examples. We hope these examples will lead you to write better one-liners of your own.