20

有没有办法让 bash 进入一种冗长的模式,这样,当它运行一个 shell 脚本时,它会在运行它之前回显它要运行的命令?也就是说,这样就可以看到已运行的命令(以及它们的输出),类似于make?的输出。

也就是说,如果运行类似的 shell 脚本

echo "Hello, World"

我想要以下输出

echo "Hello, World"
Hello, World

或者,是否可以编写一个名为 bash 的函数echo_and_run来输出命令然后运行它?

$ echo_and_run echo "Hello, World"
echo "Hello, World"
Hello, World
4

6 回答 6

35

您可以echo在调用eval.

Bash 还具有调试功能。一旦你set -xbash 将在执行之前显示每个命令。

cnicutar@shell:~/dir$ set -x
cnicutar@shell:~/dir$ ls
+ ls --color=auto
a  b  c  d  e  f
于 2012-09-01T22:09:50.187 回答
23

要回答您问题的第二部分,这里有一个 shell 函数可以满足您的要求:

echo_and_run() { echo "$*" ; "$@" ; }

我使用类似的东西:

echo_and_run() { echo "\$ $*" ; "$@" ; }

它打印$在命令的前面(它看起来像一个 shell 提示符,并且更清楚地表明它是一个命令)。当我想显示它正在执行的一些(但不是全部)命令时,我有时会在脚本中使用它。

正如其他人所提到的,它确实丢失了引号:

$ echo_and_run echo "Hello, world"
$ echo Hello, world
Hello, world
$ 

但我认为没有什么好的方法可以避免这种情况;echo_and_run在有机会看到它们之前,shell 会去掉引号。您可以编写一个脚本来检查包含空格和其他 shell 元字符的参数,并根据需要添加引号(这仍然不一定与您实际键入的引号匹配)。

于 2012-09-03T00:42:50.327 回答
7

可以将 bashprintf%q格式说明符结合使用来转义参数,以便保留空格:

function echo_and_run {
  echo "$" "$@"
  eval $(printf '%q ' "$@") < /dev/tty
}
于 2014-04-22T21:58:39.007 回答
2

有关额外的时间戳和 I/O 信息,请考虑Debiandevscriptsannotate-output中的命令:

annotate-output echo hello

输出:

13:19:08 I: Started echo hello
13:19:08 O: hello
13:19:08 I: Finished with exitcode 0

现在查找一个不存在的文件,并注意E: for STDERR输出:

annotate-output ls nosuchfile

输出:

13:19:48 I: Started ls nosuchfile
13:19:48 E: ls: cannot access 'nosuchfile': No such file or directory
13:19:48 I: Finished with exitcode 2
于 2016-06-29T17:26:23.520 回答
1

两个有用的 shell 选项可以添加到bash命令行或通过set脚本或交互式会话中的命令:

  • -v 在读取 shell 输入行时打印它们。
  • -x 在展开每个简单命令、for命令、case命令、select命令或算术for命令后,显示 的扩展值PS4,后跟命令及其扩展参数或相关单词列表。
于 2016-06-29T17:17:50.720 回答
0

为了添加到其他人的实现中,这是我的基本脚本样板,包括参数解析(如果您要切换详细级别,这很重要)。

#!/bin/sh

# Control verbosity
VERBOSE=0

# For use in usage() and in log messages
SCRIPT_NAME="$(basename $0)"

ARGS=()

# Usage function: tells the user what's up, then exits.  ALWAYS implement this.
# Optionally, prints an error message
# usage [{errorLevel} {message...}
function usage() {
    local RET=0
    if [ $# -gt 0 ]; then
        RET=$1; shift;
    fi
    if [ $# -gt 0 ]; then
        log "[$SCRIPT_NAME] ${@}"
    fi
    log "Describe this script"
    log "Usage: $SCRIPT_NAME [-v|-q]" # List further options here
    log "   -v|--verbose    Be more verbose"
    log "   -q|--quiet      Be less verbose"
    exit $RET
}

# Write a message to stderr
# log {message...}
function log() {
    echo "${@}" >&2
}

# Write an informative message with decoration
# info {message...}
function info() {
    if [ $VERBOSE -gt 0 ]; then
        log "[$SCRIPT_NAME] ${@}"
    fi
}

# Write an warning message with decoration
# warn {message...}
function warn() {
    if [ $VERBOSE -gt 0 ]; then
        log "[$SCRIPT_NAME] Warning: ${@}"
    fi
}

# Write an error and exit
# error {errorLevel} {message...}
function error() {
    local LEVEL=$1; shift
    if [ $VERBOSE -gt -1 ]; then
        log "[$SCRIPT_NAME] Error: ${@}"
    fi
    exit $LEVEL
}

# Write out a command and run it
# vexec {minVerbosity} {prefixMessage} {command...}
function vexec() {
    local LEVEL=$1; shift
    local MSG="$1"; shift
    if [ $VERBOSE -ge $LEVEL ]; then
        echo -n "$MSG: "
        local CMD=( )
        for i in "${@}"; do
            # Replace argument's spaces with ''; if different, quote the string
            if [ "$i" != "${i/ /}" ]; then
                CMD=( ${CMD[@]} "'${i}'" )
            else
                CMD=( ${CMD[@]} $i )
            fi
        done
        echo "${CMD[@]}"
    fi
    ${@}
}

# Loop over arguments; we'll be shifting the list as we go,
# so we keep going until $1 is empty
while [ -n "$1" ]; do
    # Capture and shift the argument.
    ARG="$1"
    shift
    case "$ARG" in
        # User requested help; sometimes they do this at the end of a command
        # while they're building it.  By capturing and exiting, we avoid doing
        # work before it's intended.
        -h|-\?|-help|--help)
            usage 0
            ;;
        # Make the script more verbose
        -v|--verbose)
            VERBOSE=$((VERBOSE + 1))
            ;;
        # Make the script quieter
        -q|--quiet)
            VERBOSE=$((VERBOSE - 1))
            ;;
        # All arguments that follow are non-flags
        # This should be in all of your scripts, to more easily support filenames
        # that start with hyphens.  Break will bail from the `for` loop above.
        --)
            break
            ;;
        # Something that looks like a flag, but is not; report an error and die
        -?*)
            usage 1 "Unknown option: '$ARG'" >&2
            ;;
        #
        # All other arguments are added to the ARGS array.
        *)
            ARGS=(${ARGS[@]} "$ARG")
            ;;
    esac
done
# If the above script found a '--' argument, there will still be items in $*;
# move them into ARGS
while [ -n "$1" ]; do
    ARGS=(${ARGS[@]} "$1")
    shift
done

# Main script goes here.

之后...

vexec 1 "Building myapp.c" \
    gcc -c myapp.c -o build/myapp.o ${CFLAGS}

注意:这不包括管道命令;你需要 bash -c 那些东西,或者把它们分解成中间变量或文件。

于 2016-06-29T16:34:31.737 回答