views:

117

answers:

2
  • The script have some hard-coded relative paths. I would like them to be relative to script position.

  • The script needs to change current directory as some other program (cmake) needs it.

  • The script takes some (possibly relative to caller) paths as an argument and it passes them to that program, they should be derelativized.

Questions are inline:

#!/bin/sh

# First arg should be Release or Debug    
# TODO test for that.

if test -n "$1"; then          # BTW how to test whether $1 is Debug or Release?
  BUILD_TYPE="$1"
else
  BUILD_TYPE="Release"
fi

# Set install prefix to current directory, unless second argument is given. 

if test -n "$2"; then
  INSTALL_PREFIX="$2"    # How to derelativize this path argument?
else
  INSTALL_PREFIX=bin     # How to make this path relative to script location?
fi

# Make build directory and do cmake, make, make install.

mkdir -p build/${BUILD_TYPE} && # How to make this path relative to script location?
cd build/${BUILD_TYPE} &&

cmake -D CMAKE_BUILD_TYPE=${BUILD_TYPE} \
      -D CMAKE_INSTALL_PREFIX=${INSTALL_PREFIX} \ # Possible relative to caller current directory. 
      ../../ &&             # Relative to scrip position.
make -j4 &&
make install

Is it a common problem or am I doing something in a non-standard way?

+1  A: 

1)

test $1 == "Debug"

2) Put

SCRIPT_DIR="$(dirname $0)"
ORIGINAL_DIR="$(pwd)"

at the top of the script (first non-comment line after #! line)

To make a variable absolute relative to the script:

[ "${VAR/#\//}" != "$VAR" ] || VAR="$SCRIPT_DIR/$VAR"

To make it relative to the starting directory:

[ "${VAR/#\//}" != "$VAR" ] || VAR="$ORIGINAL_DIR/$VAR"

Basically we replace a leading slash with empty "${VAR/#\//}" and compare with "$VAR", if they are different then $VAR is absolute. Otherwise we prepend a directory that we want to make it absolute.

Douglas Leeder
What about leading ./ ?
Łukasz Lew
I found readlink -f command, but I'm not sure whether it help. Can you comment?
Łukasz Lew
readlink -f deals with symlinks, not with making paths absolute. You shouldn't need to canonicalise the paths you are given, as you can read via symlinks.
Douglas Leeder
./ is a relative path, and gets treated as such. It won't cause any problems for programs to read paths containing /./ although you might want to tidy up before displaying the path to the user.
Douglas Leeder
+1  A: 

In addition to what Douglas Leeder said, I’d recommend to always surround your variables in double quotes to prevent paths with space characters messing up your script.

Bombe