gpt4 book ai didi

Bash 脚本 : how to get the whole command line which ran the script

转载 作者:行者123 更新时间:2023-12-02 04:21:13 26 4
gpt4 key购买 nike

我想运行 bash 脚本并能够看到用于启动它的命令行:

sh myscript.sh arg1 arg2 1> output 2> error

为了了解用户是否使用了“std 重定向”'1>' 和 '2>',从而调整我的脚本的输出。

可以使用内置变量吗?

谢谢。

最佳答案

在 Linux 和一些类 UNIX 系统上,/proc/self/fd/1/proc/self/fd/2 是指向您的 std 重定向 指向。使用readlink,我们可以通过将它们与父进程的文件描述符进行比较来查询它们是否被重定向。

但是,我们不会使用 self 而是使用 $$ 因为 $(readlink/proc/"$$"/fd/1) 会生成一个新的 shell,这样 self 将不再引用当前的 bash 脚本,而是引用子 shell。

$ cat test.sh
#!/usr/bin/env bash

#errRedirected=false
#outRedirected=false
parentStderr=$(readlink /proc/"$PPID"/fd/2)
currentStderr=$(readlink /proc/"$$"/fd/2)
parentStdout=$(readlink /proc/"$PPID"/fd/1)
currentStdout=$(readlink /proc/"$$"/fd/1)
[[ "$parentStderr" == "$currentStderr" ]] || errRedirected=true
[[ "$parentStdout" == "$currentStdout" ]] || outRedirected=true

echo "$0 ${outRedirected:+>$currentStdout }${errRedirected:+2>$currentStderr }$@"

$ ./test.sh
./test.sh

$ ./test.sh 2>/dev/null
./test.sh 2>/dev/null

$ ./test.sh arg1 2>/dev/null # You will lose the argument order!
./test.sh 2>/dev/null arg1

$ ./test.sh arg1 2>/dev/null >file ; cat file
./test.sh >/home/camusensei/file 2>/dev/null arg1

$

不要忘记,用户还可以重定向到在其他内容上打开的第三文件描述符......!

关于Bash 脚本 : how to get the whole command line which ran the script,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30322595/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com