首页 > 解决方案 > 从包含要执行的可执行命令的 .txt 文件中读取,将执行的命令的输出发送到另一个文件

问题描述

当我运行我的脚本时,读取 .txt 文件,将可执行命令分配给$eggs,然后执行命令并将输出重定向到我使用echo $eggs>>eggsfile.txt的文件,但是当我 cat 文件时,我只看到所有命令而不是这些命令的执行输出。


echo "Hi, $USER"
cd ~/mydata
echo -e "Please enter the name of commands file:/s"
read fname               
if [ -z "$fname" ]
then
  exit
fi

terminal=`tty`       

exec < $fname              #exec destroys current shell, opens up new shell process where FD0 (STDIN) input comes from file fname

count=1

while read line
do
  echo $count.$line                   #count line numbers
  count=`expr $count + 1`; eggs="${line#[[:digit:]]*}";
  touch ~/mydata/eggsfile.txt; echo $eggs>>eggsfile.txt; echo "Reading eggsfile contents: $(cat eggsfile.txt)"
done

exec < $terminal

标签: bash

解决方案


如果您只想执行命令,并在每个命令之前记录命令名称,则可以使用“sh -x”。您将在每个命令之前获得“+ 命令”。

sh -x commands

+pwd
/home/user
+ date
Sat Apr  4 21:15:03 IDT 2020

如果您想构建自己的(自定义格式等),则必须强制执行每个命令。就像是:

cd ~/mydata
count=0
while read line ; do
    count=$((count+1))
    echo "$count.$line"
    eggs="${line#[[:digit:]]*}"
    echo "$eggs" >> eggsfile.txt
    # Execute the line.
    ($line) >> eggsfile.txt
done < $fname

请注意,此方法对while循环使用本地重定向,避免将输入恢复到终端。


推荐阅读