20

シェルスクリプトを実行しているときに、実行する前に実行するコマンドをエコーアウトするような、一種の冗長モードにする方法はありますか? makeつまり、 ?の出力と同様に、実行されたコマンド (およびその出力) を確認できるようになります。

つまり、次のようなシェル スクリプトを実行すると、

echo "Hello, World"

次の出力が欲しい

echo "Hello, World"
Hello, World

echo_and_runまたは、コマンドを出力して実行するbash 関数を作成することは可能ですか?

$ 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 に答える
7

printfフォーマット指定子と組み合わせてbash を使用し%qて、スペースが保持されるように引数をエスケープすることができます。

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

コマンド ラインに追加するか、スクリプトまたは対話型セッションbashのコマンドを介して追加できる 2 つの便利なシェル オプション:set

  • -v シェル入力行を読み取ったときに表示します。
  • -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 に答える