Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if two paths are equal in Bash?

What's the best way to check if two paths are equal in Bash? For example, given the directory structure

~/   Desktop/     Downloads/ (symlink to ~/Downloads)   Downloads/     photo.png 

and assuming that the current directory is the home directory, all of the following would be equivalent:

./                    and ~ ~/Desktop             and /home/you/Desktop ./Downloads           and ~/Desktop/Downloads ./Downloads/photo.png and ~/Downloads/photo.png 

Is there a native Bash way to do this?

like image 406
James Ko Avatar asked Nov 29 '15 06:11

James Ko


People also ask

Does path exist bash?

Checking If a Directory Exists In a Bash Shell Script-h "/path/to/dir" ] && echo "Directory /path/to/dir exists." || echo "Error: Directory /path/to/dir exists but point to $(readlink -f /path/to/dir)." The cmd2 is executed if, and only if, cmd1 returns a non-zero exit status.

How to check if two strings are equal in Bash?

Bash Strings Equal – In this tutorial, we shall learn how to check if two strings are equal in bash scripting. To check if two strings are equal in bash scripting, use bash if statement and double equal to == operator. To check if two strings are not equal in bash scripting, use bash if statement and not equal to != operator.

What is the PATH variable in Bash?

Here come the environment variables into play, especially the PATH variable. This variable is responsible for telling bash where to look for those programs. Let’s check out how PATH works and how to view/modify PATH.

What happens when the path value is updated in Bash?

The PATH value is updated! In bash, the PATH variable is an important one. Any program that runs through the bash session inherits the variable, so it’s important that PATH includes the necessary directories only. Adding more directory will only add redundancy to the system.

How do I find the location of a command in Bash?

Most of the command tools are located under the /usr/bin directory. Here, bash is consulting PATH for the locations to search for the executable (s) of a command. Before we modify the value of PATH, it’s important to understand its structure. Run the command again to check the value of PATH.


2 Answers

Bash's test commands have a -ef operator for this purpose

if [[ ./ -ef ~ ]]; then ...  if [[ ~/Desktop -ef /home/you/Desktop ]]; then ... 

etc...

$ help test | grep -e -ef       FILE1 -ef FILE2  True if file1 is a hard link to file2. 
like image 112
geirha Avatar answered Sep 21 '22 20:09

geirha


You can use realpath. For example:

realpath ~/file.txt Result: /home/testing/file.txt  realpath ./file.txt Result: /home/testing/file.txt 

Also take a look at a similar answer here: bash/fish command to print absolute path to a file

like image 44
zedfoxus Avatar answered Sep 18 '22 20:09

zedfoxus