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

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


当前回答

pathToShell="/home/praveen/"   
chmod a+x $pathToShell"myShell.sh"
sh $pathToShell"myShell.sh"

其他回答

 #!/bin/bash

 # Here you define the absolute path of your script

 scriptPath="/home/user/pathScript/"

 # Name of your script

 scriptName="myscript.sh"

 # Here you execute your script

 $scriptPath/$scriptName

 # Result of script execution

 result=$?

上面的答案建议添加#!/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/sh调用或执行另一个脚本(通过你的实际脚本):

 # cat showdate.sh
 #!/bin/bash
 echo "Date is: `date`"

 # cat mainscript.sh
 #!/bin/bash
 echo "You are login as: `whoami`"
 echo "`/bin/sh ./showdate.sh`" # exact path for the script file

输出将是:

 # ./mainscript.sh
 You are login as: root
 Date is: Thu Oct 17 02:56:36 EDT 2013

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

#!bin/bash
./myscript.sh &

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

pathToShell="/home/praveen/"   
chmod a+x $pathToShell"myShell.sh"
sh $pathToShell"myShell.sh"