是否可以访问完整的命令行,包括 bash 脚本中的管道?

hel*_*ode 9 bash

例如命令行:

test.sh arg1 | grep "xyz"
Run Code Online (Sandbox Code Playgroud)

是否可以在 bash 脚本 test.sh 中获得包含以下 grep 的完整命令行?

Arc*_*mar 13

bash(或您的 shell)将派生出两个不同的命令。

  1. test.sh arg1
  2. grep "xyz"

test.sh 不知道跟随grep。

但是,您可能会通过测试知道自己处于管道“内部” /proc/self/fd/1

测试文件

#!/bin/bash

file /proc/self/fd/1
Run Code Online (Sandbox Code Playgroud)

运行方式

> ./test.sh
/proc/self/fd/1: symbolic link to /dev/pts/0
> ./test.sh | cat
/proc/self/fd/1: broken symbolic link to pipe:[25544239]
Run Code Online (Sandbox Code Playgroud)

(编辑)查看穆鲁关于知道你是否在管道上的评论

你不需要知道你是否在管道中。只需检查输出是否为 TTY。[ -t 1 ] https://unix.stackexchange.com/a/401938/70524


mos*_*svy 6

有没有办法做到这一点一般

但是交互式bashshell 可以利用历史机制和DEBUG陷阱来“告诉”它运行的命令通过环境变量运行完整的命令行:

$ trap 'export LC=$(fc -nl -0); LC=${LC#? }' DEBUG
$ sh -c 'printf "last_command={%s}\n" "$LC"' | cat; true
last_command={sh -c 'printf "last_command={%s}\n" "$LC"' | cat; true}
Run Code Online (Sandbox Code Playgroud)