更新时间:2022-03-28 21:44:01
您要做的是获取脚本的绝对路径(可通过${BASH_SOURCE[0]}
获得),然后使用它来获取父目录和cd
脚本开头的内容.
What you want to do is get the absolute path of the script (available via ${BASH_SOURCE[0]}
) and then use this to get the parent directory and cd
to it at the beginning of the script.
#!/bin/bash
parent_path=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P )
cd "$parent_path"
cat ../some.text
这将使您的shell脚本独立于您从何处调用它而工作.每次运行它时,就像在dir
中运行./cat.sh
一样.
This will make your shell script work independent of where you invoke it from. Each time you run it, it will be as if you were running ./cat.sh
inside dir
.
请注意,此脚本仅在您直接调用脚本(即不通过符号链接)时才有效,否则,找到脚本的当前位置会更加棘手)
Note that this script only works if you're invoking the script directly (i.e. not via a symlink), otherwise the finding the current location of the script gets a little more tricky)