bash - 从包含要执行的可执行命令的 .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
解决方案
如果您只想执行命令,并在每个命令之前记录命令名称,则可以使用“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
循环使用本地重定向,避免将输入恢复到终端。
推荐阅读
- authentication - Cakephp 3.7.x 如何检索用户数据?使用身份验证组件
- c++ - 如何修复 C++ boost http 示例中的“未找到架构 x86_64 的符号”错误
- c# - 禁用 UAC 并通知用户
- python - Django Rest Framework 用户模型序列化器嵌套
- postgresql - 我的交叉表进入功能有问题
- windows - 如何在水晶报表上动态更新 SetDatasource
- android - 未授予通话和短信权限,但仍收到来自 google play 的警告
- python - 带有回调的python上的电报机器人
- android - 如何从android中的textView获取字符串屏幕位置(y和x)?
- excel - 如何使用多个过滤器计算数据范围中的值