我有两个独立运行的脚本。第一个脚本A计算一些值。我想从另一个脚本B中输出这些值。这些脚本不会相互调用。我已经使用了export关键字,但没有起作用。我该怎么做?
如果我理解得正确,那么这两个脚本不能在同一个子shell中独立执行吗?不需要调用彼此或任何外部文件或管道,就像这样:
假设这是你的script1.sh:
#!/bin/bash
# script1.sh: do something and finally
export x=19
#!/bin/bash
# script2.sh: read value of $x here
echo "x="${x}
(. ./script1.sh && ./script2.sh)
输出:
x=19
mkfifo /tmp/channel
process_a.sh > /tmp/channel&
process_b.sh < /tmp/channel&
wait
当然,如果你只想读取一行内容,也是可以的。
在bash中,有协程(coprocs),这可能也是你想要的。以下是一个随机示例,来自此页面。
# let the output of the coprocess go to stdout
{ coproc mycoproc { awk '{print "foo" $0;fflush()}' ;} >&3 ;} 3>&1
echo bar >&${mycoproc[1]}
foobar
ksh 显然有类似的功能
“FIFO”是一种特殊的文件类型,允许独立的进程进行通信。
- glenn jackman#!/bin/sh
# a.sh: Calculate something and return the result
echo 19
而脚本B是:
#!/bin/sh
# b.sh: Consume the calculated result, which passed in as $1
echo The result is $1
chmod +x [ab].sh
$ b.sh $(a.sh)
The result is 19
source
,可以跳过export
前缀。
我的用例是一个特定环境的设置文件,例如:
在main_script.sh中。THIS_DIR=`dirname $0`
source $THIS_DIR/config_vars.sh
# other commands
在config_vars.sh文件中
LOCAL_ROOT="$HOME/folder/folder"
REMOTE_USERNAME='someuser'
BACKUP_FOLDER="$LOCAL_ROOT/folder"
# etc.
你不能读取第三个文件吗?比如说settings.sh,里面有一些常用的导出变量。
# common.sh
export MY_PATH=/home/foo/bar/
export VERSION=42.2a
在 A 和 B 中都需要使用 source common.sh
加载这些值。
请注意,在这种情况下可能不需要导出。
你可以将值回显到文件中,然后其他脚本可以读取它们。如果你想将其用作某个参数,请使用反引号:
echo `cat storedvalue`
注意,如果两个脚本同时运行,可能会出现并发问题,这可能会导致罕见的、神秘的错误。
. script
能行吗?(请参见http://www.linuxquestions.org/questions/linux-newbie-8/how-to-export-environment-variable-from-a-bash-script-344057/) - mlvljr