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?
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.
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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With