如何从bash脚本运行shell脚本

时间:2015-02-28 19:55:43

标签: bash shell

我收到错误(在线:sh up.sh)运行以下内容:

#!/bin/bash

# Install angular components 
echo "Installing Angular Components..."
cd angApp
npm install

# Install Server components
echo "Installing Backend Components..."
cd ..
cd APIServer

# go back to main dir
cd ..

# ask to see if we should launch server
echo "Do you want to launch the server now? Enter (yes/no)  "
read shouldLaunch

# Launch if requested. Otherwise end build
if [ "$shouldLaunch" == "yes" ]; then
    echo "Great! Launching the servers for you..."
    sh up.sh
else
    echo "No problem..."
    echo "you can launch the server by doing ./up.sh"
    echo "bye!"
fi

如何运行up.sh脚本?

2 个答案:

答案 0 :(得分:2)

如果up.sh文件与包含上述代码的文件位于同一目录中,那么您可以

echo "Great! Launching the servers for you..."
$(dirname $0)/up.sh

变量$0是当前脚本的路径,dirname剥离路径的最后一段,$(...)dirname的输出转换为字符串

答案 1 :(得分:1)

为避免cd混乱,只需在子shell中运行部件,例如:

#!/bin/bash

(
# Install angular components - in shubshell
echo "Installing Angular Components..."
cd angApp
npm install
)

(
# Install Server components - again in subshell
echo "Installing Backend Components..."
cd APIServer
#do something here
)    

# go back to main dir
#cd .. #not needed, you're now in the parent shell...

# ask to see if we should launch server
echo "Do you want to launch the server now? Enter (yes/no)  "
read shouldLaunch

# Launch if requested. Otherwise end build
if [ "$shouldLaunch" == "yes" ]; then
    echo "Great! Launching the servers for you..."
    sh up.sh
else
    echo "No problem..."
    echo "you can launch the server by doing ./up.sh"
    echo "bye!"
fi