2011-06-09 105 views
1

有没有更好的方式来保存命令行执行之前?如何保存你即将在bash中执行的命令?

许多my/bin/bash脚本构造了一个很长的命令行。我通常将命令行保存到文本文件中以便于调试和(有时)执行。

我的代码充斥着这个成语:

echo >saved.txt cd $NEW_PLACE '&&' command.py --flag $FOO $LOTS $OF $OTHER $VARIABLES 
       cd $NEW_PLACE && command.py --flag $FOO $LOTS $OF $OTHER $VARIABLES 

在两个地方显然更新代码很容易出错。不太明显的是,某些部分需要在第一行中引用,而不是下一部分引用。因此,我无法通过简单的复制和粘贴来进行更新。如果该命令包含引号,则会变得更加复杂。

必须有更好的方法!建议?

回答

4

有关创建它记录一个辅助函数如何这个问题,然后执行命令? "[email protected]"将扩大到在传递任何命令。

log() { 
    echo "[email protected]" >> /tmp/cmd.log 
    "[email protected]" 
} 

通过简单地在前面加上log到任何现有的命令中使用它。但它不会处理&&||,因此您必须分别记录这些命令。

log cd $NEW_PLACE && log command.py --flag $FOO $LOTS $OF $OTHER $VARIABLES 
1

您是否在寻找-x(或bash -x)?这将执行后将每个命令写入标准输出。

-1

我建议你看看xargs命令。它是为了解决程式设计建立参数列表和传递了他们对可执行文件进行批处理

http://en.wikipedia.org/wiki/Xargs

+0

我熟悉xargs的,但是我正在寻找一种方式来捕捉命令没有建立长期的命令线。 – TomOnTime 2011-06-11 12:07:20

0

如果你只是在创建后立即执行该命令文件,你只需要构建命令一次,越狱的一个水平。

如果这会创建太多离散的小命令文件,您可以创建shell过程,然后运行一个单独的命令文件。

(echo fun123 '()' { 
echo echo something important 
echo } 
) > saved.txt 
. saved.txt 
fun123 
1
  1. 使用script,您将得到归档一切。
  2. 使用-x来追踪您的脚本,例如在当前的bash运行它们为bash -x script_name args....
  3. 使用set -x(你会得到与取代的水珠和变量呼应你的命令
  4. 结合2,3与1
+0

关注他的倒票评论他的倒票?怎么了? – jm666 2011-06-11 12:56:54

0

这听起来像你的目标是保持。良好的日志的脚本做了什么,让你可以调试它,当事情变坏我会建议使用-x参数在你的家当像这样:

#!/bin/sh -x 
# the -x above makes bash print out every command before it is executed. 
# you can also use the -e option to make bash exit immediately if any command 
# returns a non-zero return code. 

此外,请参阅my answer关于redirecti前一个问题将--log传递到您的shell脚本中时,将所有此调试输出都记录到日志中。这将重定向所有stdoutstderr。有时候,你仍然想写信给终端来给用户反馈。您可以通过保存stdout到一个新的文件描述符,并使用与echo(或其他程序)做到这一点:

exec 3>&1 # save stdout to fd 3 

# perform log redirection as per above linked answer 

# now all stdout and stderr will be redirected to the file and console. 
# remove the `tee` command if you want it to go just to the file. 

# now if you want to write to the original stdout (i.e. terminal) 
echo "Hello World" >&3 

# "Hello World" will be written to the terminal and not the logs.