在自己的工作目录中运行可执行文件

时间:2013-11-02 23:11:20

标签: c++ linux bash

我在我的gvim工具栏中添加了一个按钮,该工具栏运行.sh文件。 .sh文件运行scons以在/ build子目录中构建我的c ++应用程序并运行它。问题是当应用程序运行时,其当前工作目录是包含.sh文件的文件夹(不是applications / build子目录)! 那么如何从.sh文件运行构建的c ++应用程序可执行文件(linux),以便其工作目录是包含可执行文件的文件夹?

2 个答案:

答案 0 :(得分:2)

只需

 cd $(dirname "$0")
 ./exec_test

请注意,您 需要 ./exec_test,而不是exec_test,除非该目录实际上已在PATH

答案 1 :(得分:1)

这是一个类似的例子(我不使用scons。)

我将工具栏图标添加到:

:amenu ToolBar.mytool :!/home/me/code/misc/foo.sh "%"

对我而言,当我点击此内容时,vim会在与vim相同的工作目录中运行该脚本。

foo.sh包含:

#!/bin/bash

set -e

# You should see the name of your file.
# It might just be "my_file.c"
echo "$1"
# This will tell you where your script is current cd'd to.
pwd

# `cd` to where the file passed on the command line is:
cd "$(dirname "$1")"

# Look for "CMakeLists.txt"
# You only need this loop if your build file / program might be up a few directories.
# My stuff tends to be:
# / - project root
#   CMakeLists.txt
#   src/
#     foo.c
#     bar.c
while true; do
    # We found it.
    if [[ -e "CMakeLists.txt" ]]; then
        break
    fi
    # We didn't find it. If we're at the root, just abort.
    if [[ "`pwd -P`" = "/" ]]; then
        echo "Couldn't find CMakeLists.txt." >&2
        exit 1
    fi
    cd ..
done

# I do builds in a separate directory.
cd build && make

您将CMakeLists.txt替换为SConstruct,将cd build && make替换为scons,或者替换为scons