WestCoastProjects
WestCoastProjects

Reputation: 63062

How to set shell variable to result of evaluation in OS/X

In Linux Bash I can do the following:

$ export CP=$(cat classpath.txt)

If we do "cat classpath" we see a very long output (that's why I am not reproducing here).

However in OS/X the same command results in CP is empty. What is the OS/X equivalent of that command?

2:21:59/mllib $ls -l classpath
-rw-r--r--  1 steve  staff  13162 Oct 28 12:19 classpath
12:26:46/mllib $export CP=$(cat classpath)
12:26:54/mllib $echo $CP

12:26:59/mllib $export CP=`cat classpath`
12:27:03/mllib $echo $CP

Upvotes: 0

Views: 470

Answers (2)

WestCoastProjects
WestCoastProjects

Reputation: 63062

The issue is that inside the large classpath file there was ONE entry with an asterisk:

/shared/libs/*   

By Removing that asterisk entry then the evaluation works fine.

The next step is to understand how to escape the asterisk so the full/correct classpath may be used.

UPDATE From a comment bye @chepner, i tried removing the shopt -s nullglob. That was the culprit!

12:54:38/mllib $shopt -u nullglob
12:54:45/mllib $vi classpath
12:54:53/mllib $export CP="$(cat classpath)"
12:55:00/mllib $echo $CP
/shared/scala/lib/*:/shared/mllib/mllib/target/scala-2.10/classes:

Another update The output of the $CP needs to be quoted. I had put quotes on the assignmnt side but not the usage.

e.g. echo "$CP" does work.

Upvotes: 0

chepner
chepner

Reputation: 531125

You always want to quote parameter expansions. In this case,

CP=$(cat classpath)

resulted in the value of CP containing a *. Since you had shopt -s nullglob, which causes a non-matching shell pattern to expand to the empty string rather than being treated literally, the command

echo $CP

produce the empty string, because the value of CP underwent pathname expansion, but did not match any files. If you had quoted it:

echo "$CP"

it would have output the path, since the quoted expansion would not undergo pathname expansion.


Alternatively, turning off nullglob with

shopt -u nullglob

causes an unmatched pattern to be treated literally, so that echo $CP would produce the unmatched pattern as output. I wouldn't consider this a solution, though, since it only "works" when the pattern doesn't match anything. It's better to properly quote your parameter expansions.

Upvotes: 3

Related Questions