exec

来源:互联网 发布:网络陈世美啥意思 编辑:程序博客网 时间:2024/05/19 15:20

1.使用exec重定向stdin


#! /bin/sh
exec 6<&0                 ------- 将文件描述符#6与stdin连接起来

exec < 14-3.sh          --------stdin被文件14-3.sh所取代

read a1                      -------读取文件第一行   
read a2                      -------读取文件第二行   
read a3

echo
echo "Following lines read from file."
echo "------------------------------"
echo $a1
echo $a2
echo $a3
echo;echo;echo

exec 0<&6 6<&-          ------------0<&6:恢复stdin,6<&-关闭文件描述符6
echo -n "Enter data: "
read b1
echo "Input read from stadin."
echo "----------------------"
echo "b1 = $b1"
echo
exit 0

 

2.使用exec重定向stdout

#! /bin/sh
LOGFILE=16-1.sh
exec 6>&1    ----------将6与stdout连接起来 
exec > $LOGFILE
echo -n "Logfile: "
date
echo "--------------------"
echo

echo "Output of /"ls -al/" command"
echo
ls -al
echo;echo
echo "Output of /"df/" command"
echo
df
exec 1>&6 6>&-
echo
echo "== stdout now restored to default == "
echo
ls -al
echo

exit 0

 

3.在同一个脚本中重定向stdin和stdout

#! /bin/sh
E_FILE_ACCESS=70
E_WRONG_ARGS=71
if [ ! -r "$1" ]
then
  echo "Need to specify output file."
  echo "Usage: $0 input-file output-file"
  exit $E_WRONG_ARGS
fi

if [ -z "$2" ]
then
  echo "Need to specify output file."
  echo "Usage: $0 input-file output-file"
  exit $E_FILE_ACCESS
fi

exec 4<&0
exec < $1

exec 7>&1
exec > $2

exec 1>&7 7>&-
exec 0>&4 4<&-

echo "File /"$1/" written to /"$2/" as uppercase conversion."

exit 0

 

4.避免子shell

#! /bin/sh
Lines=0
echo
cat yjg.txt | while read line   ------------管道产生子shell
do
  echo $line
  (( Line++ ))
done

echo "Number of lines read = $Lines"
echo "----------------"

exec 3<>yjg.txt  ---------打开文件,并赋给3
while read line <&3 -----------不产生子shell
do {
 echo "$line"
 (( Lines++ ));
}
done

exec 3>&-
echo "Number of lines read = $Lines"
echo

exit 0

原创粉丝点击