处理循环的输出
1.在 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,而不再显示在屏幕上。
2.考虑下面这个将 for 命令的输出重定向至文件的例子:
$ cat test23
#!/bin/bash
# redirecting the for output to a file
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
$
3.也可以用于将循环的结果传输到另一个命令:
$ cat test24
#!/bin/bash
# piping a loop to another command
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
$
实战1:查找可执行文件
$ 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
$
实战2: 创建多个用户账户
$ cat test26
#!/bin/bash
# process new user accounts
input="users.csv" #####创建一个文本文件,内容包含(loginname, name)
while IFS=',' read -r loginname name ######将 IFS 分隔符设置成逗号,并将其作为 while 语句的条件测试部分。然后使用 read 命令读取文件中的各行。
do
echo "adding $loginname"
useradd -c "$name" -m $loginname
done < "$input"
$