0

I get confused about using command directly and using $(foo). I'm using Mac, I try to list apps which is install by brew cask(a package manager), and echo each app. I have two short Shell scripts, first one like this:

#!/bin/bash
apps=$(brew cask list)
for app in ${apps}
do
    echo  "${app}"
done

It works fine, however another likes this:

#!/bin/bash
apps=$(brew cask list)
myecho=$(echo)
for app in ${apps}
do
    ${myecho}  "${app}"
done

This one returns ./script2.sh: line 7: foo: command not found, foo is the name of app. What's the difference between I use echo directly and using myecho as a aliases?

2 Answers 2

2

In this command

myecho=$(echo)

you are setting myecho to an empty token. So the following command

${myecho}  "${app}"

is simply "${app}", which is apparently "foo" (not what was intended). You would make an alias using different syntax:

alias myecho="echo"

Further reading:

2
  • Is that means no matter which command, when I use $(foo), I just got the result of executing the command rather than store it as alias?
    – Sol Alsvid
    Commented Apr 24, 2016 at 10:29
  • yes, that's correct. Commented Apr 24, 2016 at 10:31
1

You are not setting an alias. In myecho=$(echo), echo is executed, and its output (nothing, as the echo has nothing to echo) is stored in the variable myecho. This, however, has some output from echo:

$ myecho=$(echo "Hello")
$ echo "$myecho"
Hello

And the variable myecho stored it.


What I believe you want in the second script is to execute echo by using the variable myecho. That is done like this:

#!/bin/bash
apps=$(brew cask list)
myecho="echo"
for app in ${apps}
do
    ${myecho}  "${app}"
done

All the above has nothing to do with an alias. An alias is defined by this:

alias myecho='echo'

But then, the line to execute the alias should not have an $:

myecho "${apps}"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .