簡體   English   中英

如何獲得在命令行執行的命令?

[英]How can I get the command that was executed at the command line?

如果以這種方式調用腳本:

myScript.sh -a something -b anotherSomething

我的腳本中是否有一種方法可以獲取調用腳本的命令?

在第一行的腳本中,我嘗試使用:

lastCommand=!!
echo $lastCommand

但是結果始終為空。

如果我echo !! 唯一可以打印到控制台的是!! ,但是如果我做的話,請從命令行執行echo !! 我得到了最后一條命令。

我也嘗試過:

echo $BASH_COMMAND

但我在這里也變得無效。 是因為該腳本是在子Shell中調用的,因此在該子Shell的內存中沒有存儲先前的命令?

調用腳本的完整命令將是"$0" "$@" ,即命令本身后跟所有引用的參數。 這可能不是運行的確切命令,但是如果腳本是冪等的,則可以運行它以得到相同的結果:

$ cat myScript.sh 
#!/usr/bin/env bash
printf '%q ' "$0" "$@"
printf '\n'
$ ./myScript.sh -a "foo bar" -b bar
./myScript.sh -a foo\ bar -b bar 

這是我的腳本myScript.sh

#!/bin/bash
temp=`mktemp`
ps --pid $BASHPID -f > $temp 
lastCommand=`tail -n 1 $temp | xargs | cut -d ' ' -f 8-`
rm $temp
echo $lastCommand

要么

#!/bin/sh
last=`cat /proc/$$/cmdline | xargs -0`
echo $last

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM