处理循环的输出

本篇内容均摘自《Linux命令行与shell脚本编程大全》,个人认为需要重点学习的章节。【免费】Linux命令行与Shell脚本编程大全 第3版 PDF全本 21MB 百度网盘下载 - 今夕是何夕 - 博客园
在shell脚本中,你可以对循环的输出使用管道或进行重定向。这可以通过在done命令之后添加一个处理命令来实现。

for file in /home/rich/*
  do
    if [ -d "$file" ]
    then
      echo "$file is a directory"
    elif
      echo "$file is a file"
    fi
done > output.txt

shell会将for命令的结果重定向到文件output.txt中,而不是显示在屏幕上。
考虑下面将for命令的输出重定向到文件的例子:

$ cat test23
#!/bin/bash
for (( a = 1; a < 10; a++ ))
do
  echo "The number is $a"
done > test23.txt
echo "The command is finished."
$ ./test23
The command is finished.
$ cat test23.txt
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9

shell创建了文件test23.txt并将for命令的输出重定向到这个文件。 shell在for命令之后正常显示了echo语句。
这种方法同样适用于将循环的结果管接给另一个命令:

$ cat test24
#!/bin/bash
for state in "North Dakota" Connecticut Illinois Alabama Tennessee
do
  echo "$state is the next place to go"
done | sort
echo "This completes our travels"
$ ./test24
Alabama is the next place to go
Connecticut is the next place to go
Illinois is the next place to go
North Dakota is the next place to go
Tennessee is the next place to go
This completes our travels

state值并没有在for命令列表中以特定次序列出。 for命令的输出传给了sort命令,该命令会改变for命令输出结果的顺序。运行这个脚本实际上说明了结果已经在脚本内部排好序了。

查找可执行文件
当你从命令行中运行一个程序的时候, Linux系统会搜索一系列目录来查找对应的文件。这些目录被定义在环境变量PATH中。如果你想找出系统中有哪些可执行文件可供使用,只需要扫描PATH环境变量中所有的目录就行了。如果要徒手查找的话,就得花点时间了。不过我们可以编写一个小小的脚本,轻而易举地搞定这件事。首先是创建一个for循环,对环境变量PATH中的目录进行迭代。处理的时候别忘了设置IFS分隔符。

IFS=:
for folder in $PATH
do

现在你已经将各个目录存放在了变量folder中,可以使用另一个for循环来迭代特定目录中的所有文件。

for file in $folder/*
do

最后一步是检查各个文件是否具有可执行权限,你可以使用if-then测试功能来实现。

if [ -x $file ]
then
echo " $file"
fi

将这些代码片段组合成脚本就行了。

$ cat test25
#!/bin/bash
# finding files in the PATH
IFS=:
for folder in $PATH
do
  echo "$folder:"
  for file in $folder/*
  do
    if [ -x $file ]
    then
      echo "  $file"
    fi
  done
done

运行这段代码时,你会得到一个可以在命令行中使用的可执行文件的列表。

$ ./test25 | more
/usr/local/bin:
/usr/bin:
/usr/bin/Mail
/usr/bin/Thunar
/usr/bin/X
/usr/bin/Xorg
/usr/bin/[
/usr/bin/a2p
/usr/bin/abiword
/usr/bin/ac
/usr/bin/activation-client
/usr/bin/addr2line

输出显示了在环境变量PATH所包含的所有目录中找到的全部可执行文件。

你可能感兴趣的:(处理循环的输出)