Subtle Development Space
Subtle Development Space

Reputation: 1254

running an executable in its own working directory

I added a button to my gvim toolbar which runs a .sh file. The .sh file runs scons to build my c++ application in the /build subdirectory and runs it. The problem is that when the application is running, its current working directory is the folder that contains the .sh file (not the applications /build subdirectory)! So how do I run a built c++ applications executable (linux) from a .sh file, so that its working directory would be the folder which contains executable?

Upvotes: 1

Views: 2273

Answers (2)

Thanatos
Thanatos

Reputation: 44256

Here's an example of something similar (I don't use scons.)

I add my toolbar icon with:

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

For me, when I click this, vim runs the script in the same working directory as vim.

foo.sh contains:

#!/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

You'd replace CMakeLists.txt with SConstruct, and the last cd build && make with scons, or something appropriate to scons.

Upvotes: 1

sehe
sehe

Reputation: 392954

Just

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

Note, you need ./exec_test, not exec_test unless the directory is actually already in PATH

Upvotes: 4

Related Questions