2009-10-08 138 views
1
  • 该脚本有一些硬编码的相对路径。我希望他们相对于剧本位置。如何在bash程序中正确地进行路径处理?

  • 脚本需要更改当前目录,因为其他程序(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 

它是一个普遍的问题还是我在一个非标准的方式做的事情?

+0

我不要求你重制脚本,我只需要一个指导如何以正确的方式做到这一点。 – 2009-10-08 09:57:36

回答

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是绝对的。否则,我们会预先安排一个我们想要使其成为绝对的目录。

+0

领先./?怎么样? – 2009-10-08 11:19:51

+0

我发现readlink -f命令,但我不确定它是否有帮助。你能评论吗? – 2009-10-08 11:43:11

+0

readlink -f处理符号链接,而不是使路径成为绝对路径。您不需要通过canonicalise给出的路径,因为您可以通过符号链接读取。 – 2009-10-08 11:58:24

1

除了什么Douglas Leeder说,我建议你到总是围绕在双引号中的变量,以防止空格字符搞乱你的脚本路径。

相关问题