0

我编写了以下 bash 函数。它应该打印一个命令,运行它并打印它的输出,并打印一个简短的描述。

#!/bin/bash

print_and_run_command() {
    COMMAND="$1"
    DESCRIPTION="$2"
    OUTPUT="`$COMMAND`"
    printf "%-30s %-30s %s\n" "$COMMAND" "$OUTPUT" "$DESCRIPTION"
}

print_and_run_command "date +%S" "Second"
print_and_run_command" date +%H" "Hour"
print_and_run_command "date +%Y-%m-%dT%H:%M:%S%z" "T-separated rfc 3339 / ISO 8601"

从 shell 执行时,每个日期命令都能正常工作。但是,在运行脚本时,会发生一个奇怪的错误:

date +%S                       34                             Second
./blah.sh: line 11: print_and_run_command date +%H: command not found
date +%Y-%m-%dT%H:%M:%S%z      2013-07-30T14:20:34-0700       T-separated rfc 3339 / ISO 8601

运行date +%H失败,即使date +%S复杂的date +%Y-%m-%dT%H:%M:%S%z工作也很好。

有什么想法失败了print_and_run_command" date +%H" "Hour"吗?

4

1 回答 1

1

好吧,让set -x我们来看看实际发生了什么。

+ print_and_run_command 'date +%S' Second
+ COMMAND='date +%S'
+ DESCRIPTION=Second
++ date +%S
+ OUTPUT=13
+ printf '%-30s %-30s %s\n' 'date +%S' 13 Second
date +%S                       13                             Second
+ 'print_and_run_command date +%H' Hour
./oh.sh: line 13: print_and_run_command date +%H: command not found
+ print_and_run_command 'date +%Y-%m-%dT%H:%M:%S%z' 'T-separated rfc 3339 / ISO 8601'
+ COMMAND='date +%Y-%m-%dT%H:%M:%S%z'
+ DESCRIPTION='T-separated rfc 3339 / ISO 8601'
++ date +%Y-%m-%dT%H:%M:%S%z
+ OUTPUT=2013-07-31T01:24:13+0400
+ printf '%-30s %-30s %s\n' 'date +%Y-%m-%dT%H:%M:%S%z' 2013-07-31T01:24:13+0400 'T-separated rfc 3339 / ISO 8601'
date +%Y-%m-%dT%H:%M:%S%z      2013-07-31T01:24:13+0400       T-separated rfc 3339 / ISO 8601
+ set +x

所以这是你的错误:

print_and_run_command" date +%H" "Hour"

它应该是

print_and_run_command "date +%H" "Hour"

print_and_run_command" date +%H" "Hour"由于print_and_run_command" date +%H"扩展print_and_run_command date +%H为 shell 的未知命令而失败。

于 2013-07-30T21:26:41.740 回答