Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if relative or absolute path in shell program

Tags:

linux

shell

path

As stated in the title, I need to determine when a program is ran if the path is relative or absolute:

./program #relative dir/dir2/program #relative ~User/dir/dir2/program #absolute /home/User/dir/dir2/program #absolute 

This are my test cases. How exactly could I go about doing this in a shell program?

Or more generally, how to check if a path, $0 in this case, is relative or absolute?

like image 413
Jordan Avatar asked Jul 09 '12 21:07

Jordan


People also ask

How can you tell if a path is relative or absolute?

In simple words, an absolute path refers to the same location in a file system relative to the root directory, whereas a relative path points to a specific location in a file system relative to the current directory you are working on.

What is absolute path in Shell?

An absolute path is defined as the specifying the location of a file or directory from the root directory(/). In other words we can say absolute path is a complete path from start of actual filesystem from / directory.

How do I find the path of a file in Shell?

Firstly, we use the dirname command to find the directory in which a file is located. Then we change the directory using the cd command. Next, we print the current working directory using the pwd command. Here, we have applied the -P option to show the physical location instead of the symbolic link.


1 Answers

if [[ "$0" = /* ]] then    : # Absolute path else    : # Relative path fi 
like image 124
Jirka Hanika Avatar answered Oct 09 '22 04:10

Jirka Hanika