Bash 返回到原路径

Bash中,运行指定路径BASE_DIR命令,结束时返回原路径BACK_DIR
可以实现配置和脚本分离。

调用命令

通过固定的cd参数$BASE_DIR$BACK_DIR调用,更改命令工作目录。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/bin/bash

BACK_DIR=$(pwd)
fun_init_shdir
BASE_DIR=$SHDIR
# REAL_DIR=$(cd $(dirname $(readlink -f "${BASH_SOURCE[0]}")) && pwd )
cd $BASE_DIR
echo "==== cd base ===="

echo "bash 脚本路径 $(pwd)"

cd $BACK_DIR
echo "==== cd back ===="
fun_init_shdir() {
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do
# resolve $SOURCE until the file is no longer a symlink
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
SOURCE="$(readlink "$SOURCE")"
[[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
# if $SOURCE was a relative symlink, resolve it relative to the path where the symlink file was located
done
SHDIR=$( cd -P "$( dirname "$SOURCE" )" && pwd )
}
0%