Search code examples
bashdatebackticks

Bash: Execute command with spaces in quotes using backticks


I've written the following bash function. 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. 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.

Any ideas what is failing the print_and_run_command" date +%H" "Hour"?


Solution

  • Well, let set -x help us to see what is actually going on.

    + 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.