[英]Bash: Execute command with spaces in quotes using backticks
I've written the following bash function. 我编写了以下bash函数。 It is supposed to print a command, run it and print its output, and print a short description.
应该打印一个命令,运行它并打印其输出,然后打印简短说明。
#!/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"
Each of the date commands works well when executed from a shell. 从shell执行时,每个date命令都可以很好地工作。 However, when running the script, a strange error happens:
但是,在运行脚本时,会发生一个奇怪的错误:
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
Running date +%H
fails, even though date +%S
and the complicated date +%Y-%m-%dT%H:%M:%S%z
work just fine. 即使
date +%S
和复杂的date +%Y-%m-%dT%H:%M:%S%z
正常运行,运行date +%H
也会失败。
Any ideas what is failing the print_and_run_command" date +%H" "Hour"
? 任何想法都使
print_and_run_command" date +%H" "Hour"
失败吗?
Well, let set -x
help us to see what is actually going on. 好吧,让
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
So here is your error: 所以这是你的错误:
print_and_run_command" date +%H" "Hour"
It should be 它应该是
print_and_run_command "date +%H" "Hour"
print_and_run_command" date +%H" "Hour"
fails because of print_and_run_command" date +%H"
expanded to print_and_run_command date +%H
which is an unknown command for shell. print_and_run_command" date +%H" "Hour"
失败,因为将print_and_run_command" date +%H"
扩展为print_and_run_command date +%H
,这是Shell的未知命令。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.