tflutre
tflutre

Reputation: 3546

specifying operand to dirname as a bash variable inside echo

Here is the one-liner I'm interested in (especially in the variable out):

find ~ | head -3 | while read f; do out=$(dirname ${f}); echo ${out}; done

I need to echo this one-liner before piping it into another program, but it fails:

echo "find ~ | head -3 | while read f; do out=$(dirname ${f}); echo ${out}; done"

with the following message:

dirname: missing operand
Try `dirname --help' for more information.
find ~ | head -3 | while read f; do out=; echo ; done

So I use single and double quotes:

echo "find ~ | head -3 | while read f; do out=$(dirname "'${f}'"); echo "'${out}'"; done"

which returns without error:

find ~ | head -3 | while read f; do out=.; echo ${out}; done

But $(dirname ${f}) isn't echoed as is.

Any idea how to do it?

Upvotes: 0

Views: 234

Answers (3)

Abhinandan prasad
Abhinandan prasad

Reputation: 1079

I don't know why You need to print with echo only. But if you want in that way only then refer below:

echo `find ~ | head -3 | while read f; do out=$(dirname ${f}); echo ${out}; done`

Upvotes: 0

Lohit Gupta
Lohit Gupta

Reputation: 1081

Use a variable to store the command and echo the variable:

cmd='find ~ | head -3 | while read f; do out=$(dirname ${f}); echo ${out}; done'
echo $cmd

Upvotes: 0

Nahuel Fouilleul
Nahuel Fouilleul

Reputation: 19315

to prevent substitution use single quotes or escape $ :

echo 'find ~ | head -3 | while read f; do out=$(dirname ${f}); echo ${out}; done'

echo "find ~ | head -3 | while read f; do out=\$(dirname \${f}); echo \${out}; done"

Upvotes: 1

Related Questions