1
  • 该脚本有一些硬编码的相对路径。我希望它们与脚本位置相关。

  • 该脚本需要更改当前目录,因为其他程序(cmake)需要它。

  • 该脚本将一些(可能相对于调用者的)路径作为参数,并将它们传递给该程序,它们应该被去相关化。

问题是内联的:

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

这是一个常见问题还是我以非标准方式做某事?

4

2 回答 2

1

除了Douglas Leeder所说的之外,我还建议您始终用双引号将变量括起来,以防止带有空格字符的路径弄乱您的脚本。

于 2009-10-08T10:16:01.617 回答
1

1)

test $1 == "Debug"

2) 放

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

在脚本的顶部(一行一行的第一个非注释#!行)

要使变量相对于脚本是绝对变量:

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

使其相对于起始目录:

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

基本上我们用空替换前导斜杠并"${VAR/#\//}"与比较"$VAR",如果它们不同,那么$VAR是绝对的。否则,我们会添加一个我们想要使其成为绝对目录的目录。

于 2009-10-08T10:10:44.903 回答