我有两个shell脚本,a.sh和b.sh。

我如何从shell脚本a.sh调用b.sh ?


当前回答

使用引号。

$ ./script-that-consumes-argument.sh `sh script-that-produces-argument.sh`

然后获取生产者脚本的输出,作为消费者脚本的参数。

其他回答

只需在一行中添加您在终端中输入的任何内容来执行脚本! 例如:

#!bin/bash
./myscript.sh &

如果要执行的脚本不在同一目录下,请使用脚本的完整路径。 例如:“/ home / user /脚本目录/。/ myscript.sh &

pathToShell="/home/praveen/"   
chmod a+x $pathToShell"myShell.sh"
sh $pathToShell"myShell.sh"
chmod a+x /path/to/file-to-be-executed

那是我唯一需要的东西。一旦要执行的脚本像这样可执行,您(至少在我的情况下)在调用脚本时不需要任何其他额外的操作,如sh或./。

感谢@Nathan Lilienthal的评论

上面的答案建议添加#!/bin/bash行到被调用的下标脚本的第一行。但是即使你添加了shebang,在子shell中运行脚本并捕获输出也要快得多:

$(源SCRIPT_NAME)

当你想要继续运行同一个解释器(例如,从bash到另一个bash脚本)并确保子脚本的shebang行不被执行时,这是有效的。

例如:

#!/bin/bash
SUB_SCRIPT=$(mktemp)
echo "#!/bin/bash" > $SUB_SCRIPT
echo 'echo $1' >> $SUB_SCRIPT
chmod +x $SUB_SCRIPT
if [[ $1 == "--source" ]]; then
  for X in $(seq 100); do
    MODE=$(source $SUB_SCRIPT "source on")
  done
else
  for X in $(seq 100); do
    MODE=$($SUB_SCRIPT "source off")
  done
fi
echo $MODE
rm $SUB_SCRIPT

输出:

~ ❯❯❯ time ./test.sh
source off
./test.sh  0.15s user 0.16s system 87% cpu 0.360 total

~ ❯❯❯ time ./test.sh --source
source on
./test.sh --source  0.05s user 0.06s system 95% cpu 0.114 total

*例如,当病毒或安全工具在设备上运行时,可能需要额外的100ms来执行一个新进程。

首先,你必须包含你调用的文件:

#!/bin/bash
. includes/included_file.sh

然后像这样调用函数:

#!/bin/bash
my_called_function