0

I want to design bash script in unix and this bash return full path because I want to use this file in other places.

Lucas Kauffman
  • 16,818
  • 9
  • 57
  • 92
Mohammad AL-Rawabdeh
  • 1,592
  • 12
  • 30
  • 54
  • Full path of what? Self, as in the full path of the running script or some other object? A text string passed to your script as an argument? – Caleb Oct 04 '10 at 14:10
  • critically you did not say whether you are executing or sourcing the script as it imparts very different approaches to solving the path question – Scott Stensland Mar 15 '18 at 02:28

3 Answers3

2

Give this a try if you have readlink on your system:

readlink -e filename
Dennis Williamson
  • 60,515
  • 14
  • 113
  • 148
1

Are you looking for the full path and filename of the running script?

#!/bin/bash

_my_name=basename $0

if [ "echo $0 | cut -c1" = "/" ]; then

 _my_path=`dirname $0`

else

 _my_path=`pwd`/`echo $0 | sed -e s/$_my_name//`

fi

echo " Filename: $_my_name"

echo "Absolute path: $_my_path"

echo "Full Path + Name: $0"

racyclist
  • 624
  • 5
  • 9
0

Since this question is not trying to answer the harder question of converting a path with symbolic links into a physical path (w/o any links), but rather just get the directory and/or full path to the original script, there is a simpler solution (broken down in this example into components for legibility, plus you may want to use any of these pieces individually):

#!/bin/bash
PROG_PATH=${BASH_SOURCE[0]}      # this script's name
PROG_NAME=${PROG_PATH##*/}       # basename of script (strip path)
PROG_DIR=$(cd "$(dirname "${PROG_PATH:-$PWD}")" 2>/dev/null 1>&2 && pwd)

echo "script directory is: $PROG_DIR"

Your test cases should involve calling this script with an absolute path, relative path, "sourcing" it, etc., and always ending up with the directory containing the script.

michael
  • 384
  • 1
  • 5