Shell脚本中的VERBOSE环境

时间:2018-10-19 08:19:09

标签: bash shell

我正在尝试编写一个Bash脚本,该脚本编译并运行当前目录中的所有C文件。我的Bash脚本如下:

#!/bin/bash

LIST="$(ls *.c)"
echo "Compile all C source files"

for f in $( ls *.c); do
    #echo "C file: $f"
    gcc $f -o "${f%.*}"
    ./"${f%.*}"

done

现在,我正在尝试定义一个VERBOSE环境变量。如果设置了VERBOSE环境变量,那么我的Bash脚本应显示用于编译源文件的命令。

如何在此Bash脚本中定义这样的VERBOSE环境变量?

定义了详细内容后,我的输出应类似于

    Compiling all C source files:
    gcc copyfile.c -o copyfile
    ---- successful ----
    gcc haserror.c -o haserror
    haserror.c: In function ‘main’:
    haserror.c:9:10: warning: missing terminating " character
    printf("Hello !\n);
    ^
    haserror.c:9:10: error: missing terminating " character
    printf("Hello!\n);
    ^~~~~~~~~~~~~~~~~~~
    haserror.c:11:1: error: expected expression before ‘}’ token
    }
    ^
    haserror.c:11:1: error: expected ‘;’ before ‘}’ token
    gcc hello.c -o hello
    ---- successful ----
    gcc p005.c -o p002
    ---- successful ----
    gcc p103.c -o p101
    ---- successful ----
    gcc p102.c -o p105
    ---- successful ----
    ============
    5 C source files are compiled successfully.
    1 C source files have compilation error(s).

**Otherwise, when my VERBOSE not defined, my output should be like**

Compiling all C source files:
haserror.c: In function ‘main’:
haserror.c:9:10: warning: missing terminating " character
printf("Hello!\n);
^
haserror.c:9:10: error: missing terminating " character
printf("Hello!\n);
^~~~~~~~~~~~~~~~~~~
haserror.c:11:1: error: expected expression before ‘}’ token
}
^
haserror.c:11:1: error: expected ‘;’ before ‘}’ token
============
5 C source files are compiled successfully.
1 C source files have compilation error(s).

1 个答案:

答案 0 :(得分:2)

显而易见的工作。

#!/bin/bash
[ "$VERBOSE" ] && echo "$0: Compile all C source files" >&2

for f in *.c; do
    [ "$VERBOSE" ] && echo "$0: C file: $f" >&2
    # [ "$VERBOSE" ] && set -x
    gcc $f -o "${f%.*}"
    # set +x
    ./"${f%.*}"
done

还请注意如何避免使用useless (and slightly dangerous) use of ls并将诊断输出打印为标准错误,并在消息中包含脚本名称。

条件很简单;当[ "$VERBOSE" ]设置为非空时,VERBOSE的计算结果为true(返回零退出代码)。您可以使用Shell的常规流控制语句有条件地执行任意复杂的操作,例如

if [ "$VERBOSE" ]; then
    echo "$0: compiling $f" >&2
    (set -x; gcc "$f" -o "${f.c}") &&
    echo "$0: ----- $f: successful -----" >&2
else
    gcc "$f" -o "${f.c}"
fi

(尽管我也许还会将编译命令重构为一个单独的函数。)

更好的设计是让脚本接受命令行选项。另外,您应该避免对私有变量使用大写字母。