【问题标题】:Would it be possible to print the file used to redirect STDERR?是否可以打印用于重定向 STDERR 的文件?
【发布时间】:2019-03-20 00:56:29
【问题描述】:

如果给出以下示例命令,是否可以打印用于重定向 STDERR 的文件名:

command.sh 2>file.err

command.sh 中的代码:

#!/bin/sh
ls -l non_existing_file.txt
echo "STDERR file is: $stderrFilename" # variable should print file.err

【问题讨论】:

  • lsof 命令;您正在寻找与当前进程的文件描述符 2 关联的文件。
  • 谢谢,但没有安装 lsof。
  • (这是有实际原因,还是只是学术问题?)
  • @LorinczyZsigmond,既有学术性又有实际原因。我有一个通用脚本,可以读取任何人都可以使用的文件,但标准错误文件名可以由他们决定。文件名将附加到日志文件中。希望我的意图足够清楚:)
  • 这样的日志文件有什么用处?假设您有很多条目,例如 /dev/pts/3/tmp/err.172923/home/joe/check-and-remove.log,那么您打算如何处理它们?

标签: shell aix


【解决方案1】:

这有点冒险,但您可以尝试解析 AIX 的 procfiles 输出。它涉及捕获 stderr 设备的主要和次要编号以及 inode 编号,然后查找相应的设备及其挂载点,然后使用 find 查找具有给定 inode 编号的文件:

#!/bin/sh
dev=$(procfiles $$ | awk '$1 == "2:" { print substr($4, 5) }')
inode=$(procfiles $$ | awk '$1 == "2:" { print substr($5, 5) }')

major=${dev%%,*}
minor=${dev##*,}

if [ "$major}" -eq 0 ]
then
  echo I give up, the major number is zero
  exit 1
fi

for file in /dev/*
do
  [ -b "$file" ] || continue
  if istat "$file" | grep -q "^Major Device ${major}.*Minor Device ${minor}$"
  then
    break
  fi
done

fs=$(mount | awk '$1 == "'"${file}"'" { print $2 }')
stderrFilename=$(find "$fs" -inum "$inode")

【讨论】:

  • 我会努力解决这个问题的。
【解决方案2】:

我使用历史提出了一个解决方案。不确定是否有更简单的方法(或适当的方法)。

#!/bin/sh
stderrfname=`history | tail -1 | awk '{ print $3 }' | sed "s/.*>//"`
echo "STDERR file is: $stderrfname"

【讨论】:

  • 暂时用这个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-29
  • 2022-08-20
  • 2014-07-22
  • 1970-01-01
  • 2021-01-18
  • 2021-06-29
  • 1970-01-01
相关资源
最近更新 更多