bash - 从中​​运行脚本

Ger*_*ard 7 linux macos bash shell

所以我正在学习一些bash,我正在试图弄清楚如何从脚本运行目录.因为我有我的脚本~/scripts/bash/myscript,如果我执行我的scipt像:

user@localhost ~/dir/I/need/to/run/the/script/from $ ~/scripts/bash/myscript
Run Code Online (Sandbox Code Playgroud)

从我的脚本中,我如何获得正在执行它的目录,以便我得到~/dir/I/need/to/run/the/script/from这种情况.快捷方式如:

DIR=`pwd`
DIR="$(cd "$(dirname "$0")" && pwd)"
DIR=`dirname $0`
Run Code Online (Sandbox Code Playgroud)

据我可以看到,他们都分配路径到脚本DIR,但我在寻找剧本是从运行的路径.

对此有何帮助?

谢谢!!:)

gle*_*man 11

$PWD变量可能是你所需要的.

$ cat >/tmp/pwd.bash <<'END'
#!/bin/bash
echo "\$0=$0"
echo "\$PWD=$PWD"
END

$ chmod u+x /tmp/pwd.bash

$ pwd
/home/jackman

$ /tmp/pwd.bash
$0=/tmp/pwd.bash
$PWD=/home/jackman
Run Code Online (Sandbox Code Playgroud)

  • 您可以这样做:`scriptdir = $(dirname-“ $(realpath-” $ 0“)”)` (2认同)