Shell script current directory?

喜欢而已 提交于 2020-06-22 05:08:56

问题


What is current directory of shell script? I this current directory from which I called it? Or this directory where script located?


回答1:


The current(initial) directory of shell script is the directory from which you have called the script.




回答2:


As already mentioned, the location will be where the script was called from. If you wish to have the script reference it's install location, it's quite simple. Below is a snippet that will print the PWD and the installed directory

#!/bin/bash
echo "Script executed from: ${PWD}"

BASEDIR=$(dirname $0)
echo "Script location: ${BASEDIR}"



回答3:


Most answers get you the current path and are context sensitive. In order to run your script from any directory, use the below snippet.

DIR="$( cd "$( dirname "$0" )" && pwd )"

By switching directories in a subshell, we can then call pwd and get the correct path of the script regardless of context.

You can then use $DIR as "$DIR/path/to/file"




回答4:


You could do this yourself by checking the output from pwd when running it. This will print the directory you are currently in. Not the script.

If your script does not switch directories, it'll print the directory you ran it from.




回答5:


To print the current working Directory i.e. pwd just type command like:

echo "the PWD is : ${pwd}"


来源:https://stackoverflow.com/questions/9889938/shell-script-current-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!