有一些方法可以将命令串联起来。简单的如一个 ;,复杂的如根据某些条件运行的逻辑链。第三种是管道命令,它能有效地将输出数据移交给链中的下一条命令。
Section 48.1: 计算文本模式的出现次数
使用管道可以将一条命令的输出作为下一条命令的输入。
ls -1 | grep -c ".conf"
在这种情况下,ls 命令的输出将作为 grep 命令的输入。结果将是名称中包含“.conf ”的文件数量。
根据需要,可以用它来构建后续命令链:
ls -1 | grep ".conf" | grep -c .
Section 48.2: 将 root cmd 输出转到用户文件
通常情况下,我们希望向其他用户显示 root 用户执行命令的结果。使用 tee 命令就可以轻松地从以 root 身份运行的命令中写入包含用户权限的文件:
su -c ifconfig | tee ~/results-of-ifconfig.txt
只有 ifconfig 以 root 身份运行。
Section 48.3: 使用 && 和 || 进行命令的逻辑编排
&& 链接两条命令。只有当第一个命令成功退出时,第二个命令才会运行。|| 链接两条命令。但只有当第一个命令失败退出时,第二个命令才会运行。
[ a = b ] && echo "yes" || echo "no"
# if you want to run more commands within a logical chain, use curly braces
# which designate a block of commands
# They do need a ; before closing bracket so bash can diffentiate from other uses
# of curly braces
[ a = b ] && { echo "let me see."
echo "hmmm, yes, i think it is true" ; } \
|| { echo "as i am in the negation i think "
echo "this is false. a is a not b." ; }
# mind the use of line continuation sign \
# only needed to chain yes block with || ....
Section 48.4: 用分号串联命令链
分号只分隔两条命令。
echo "i am first" ; echo "i am second" ; echo " i am third"
Section 48.5: 用 | 命令串联命令
| 获取左侧命令的输出,并将其作为右侧命令的输入。请注意,这是在子shell中进行的。因此不能在管道中设置调用进程的 vars 值。
find . -type f -a -iname '*.mp3' | \
while read filename; do
mute --noise "$filename"
done