jwd
jwd

Reputation: 11114

Bash: How do I properly quote the results of a command

My problem boils down to this:

echo $(echo '*')

That outputs the names of all the files in the current directory. I do not want that. I want a literal asterisk (*).

How do I do this in a generic way?

My above example is simplified. The asterisk is not literally written in my bash script - it comes from the result of another command.

So this is perhaps closer to my real situation:

echo $(my-special-command)

I just want to get the literal output of my-special-command; I do not want any embedded asterisks (or other special characters) to be expanded.

How do I do this in a general-purpose way?

I suppose I could do set -f before running the command, but how can I be sure that covers everything? That turns off pathname expansion, but what about other kinds? I have zero control over what output might be produced by my-special-command, so must be able to handle everything properly.

Upvotes: 1

Views: 62

Answers (3)

chepner
chepner

Reputation: 531225

From the "Command Substitution" section of the man page:

If the [command] substitution appears within double quotes, word splitting and pathname expansion are not performed on the results.

By quoting the command expansion, you prevent its result, *, from undergoing pathname expansion.

$ echo "$(echo "*")"

Upvotes: 1

Andreas Louv
Andreas Louv

Reputation: 47099

Its called globbing, you have multiply ways to prevent it:

echo * # will expand to files / directories
echo "*" # Will print *
echo '*' # Will also print *

In your example you can simple write:

echo "$(echo '*')"

You can also turn off globbing in your script by calling it with bash -f script.sh or inside your code:

#!/usr/bin/env bash
set -f
echo *

Upvotes: 1

whoan
whoan

Reputation: 8521

Just enclose the Command substitution with double quotes:

echo "$(my-special-command)"

Upvotes: 3

Related Questions