开发者

shell scripting: nested subshell ++

More than a problem, this is a request for "another way to do this".

Actually, if I want to use the result of a previous command in another one, I use:

R1=$("cat somefile |  awk '{ print $1 }'" )
myScript -c $R1 -h123

then, a "better way" is:

myScript -c $("cat somefile |  awk '{ print $1 }'" ) -h123

But what if I have to use the result several times? Let'开发者_高级运维s say: using several times $R1, well the 2 options are:

Option 1

R1=$("cat somefile | awk '{ print $1}'")

myScript -c $R1 -h123 -x$R1

option 2

myScript -c $("cat somefile |  awk '{ print $1 }'" ) -h123 -x $("cat somefile |  awk '{ print $1 }'" )

Do you know another way to "store" the result of a previous command/script and use it as a argument into another command/script?


Sure, there are other ways. They're just not better ways.

First, you could store the answer in a file, and then cat the contents of the file multiple times.

Second, you could pass the results to a bash function like:

callMyScript() {
   myScript -c "$1" -h123 -x "$1" 
}

invoked thusly:

callMyScript "$(awk '{ print $1; }' somefile)"

which is almost precisely identical to just saving off into a local variable.

So you're interested in using awk? You could have awk generate the line for you, and have bash run it:

eval $(awk '{ printf "myScript -c %s -h123 -x %s\n", $1, $1; }' somefile)

but now we're just getting silly, and even that's no different conceptually from simply saving off into a variable.

My advice: Use the variable.


Another not perfect way:

source script #1, then when script #2 runs all of the variables declared in #1 are available to #2.

#!/bin/ksh
.  myScript -c $("cat somefile |  awk '{ print $1 }'" ) -h123 
myScript2 

Your best choice is a wrapper script that keeps all your variables for you, as everyone else already noted.

In bash the source builtin command is the same as the 'dot'

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜