Unix shell script find out which directory the script file resides?

基本上我需要使用与脚本文件位置相关的路径运行脚本,如何将当前目录更改为脚本文件所在的同一目录?


在Bash中,你应该得到你需要的这样的东西:

#!/usr/bin/env bash

BASEDIR=$(dirname "$0")
echo "$BASEDIR"

The original post contains the solution (ignore the responses, they don't add anything useful). The interesting work is done by the mentioned unix command readlink with option -f . Works when the script is called by an absolute as well as by a relative path.

For bash, sh, ksh:

#!/bin/bash 
# Absolute path to this script, e.g. /home/user/bin/foo.sh
SCRIPT=$(readlink -f "$0")
# Absolute path this script is in, thus /home/user/bin
SCRIPTPATH=$(dirname "$SCRIPT")
echo $SCRIPTPATH

For tcsh, csh:

#!/bin/tcsh
# Absolute path to this script, e.g. /home/user/bin/foo.csh
set SCRIPT=`readlink -f "$0"`
# Absolute path this script is in, thus /home/user/bin
set SCRIPTPATH=`dirname "$SCRIPT"`
echo $SCRIPTPATH

See also: https://stackoverflow.com/a/246128/59087


Assuming you're using bash

#!/bin/bash

current_dir=$(pwd)
script_dir=$(dirname $0)

echo $current_dir
echo $script_dir

This script should print the directory that you're in, and then the directory the script is in. For example, when calling it from / with the script in /home/mez/ , it outputs

/
/home/mez

Remember, when assigning variables from the output of a command, wrap the command in $( and ) - or you won't get the desired output.

链接地址: http://www.djcxy.com/p/36186.html

上一篇: 如何在Unix控制台或Mac终端上运行shell脚本?

下一篇: Unix shell脚本找出脚本文件所在的目录?