使用文件描述符执行命令

使用文件描述符执行命令

当我将其作为 shell 脚本执行时,以下 unix 命令运行正常:

#!/bin/bash
# Redirecting stdin using 'exec'.


exec 6<&0          # Link file descriptor #6 with stdin.
                   # Saves stdin.

exec < data-file   # stdin replaced by file "data-file"

read a1            # Reads first line of file "data-file".
read a2            # Reads second line of file "data-file."

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

echo; echo; echo

exec 0<&6 6<&-
#  Now restore stdin from fd #6, where it had been saved,
#+ and close fd #6 ( 6<&- ) to free it for other processes to use.
#
# <&6 6<&-    also works.

echo -n "Enter data  "
read b1  # Now "read" functions as expected, reading from normal stdin.
echo "Input read from stdin."
echo "----------------------"
echo "b1 = $b1"

echo

exit 0

但是,当我在终端中单独执行命令时,以下命令出现“未找到命令”错误:

exec < data-file

答案1

如果你给出命令exec < file,那么当前 bash shell 将从文件,而不是 std-in。

我假设当您在终端中单独输入命令时,exec 命令会正常工作,并且您当前的(交互式)bash shell 会开始读取data-file(而不是您的键盘)。我猜数据文件不包含 bash 命令,因此 bash 会响应“未找到命令”。

相关内容