iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🏹

How to Correctly Detect if a File is Shared via Symbolic Links

に公開

You might think that you can tell whether a file's actual entity is located elsewhere via a symbolic link (shared across multiple paths) or not simply by running the ls -l command.

$ ls -l
./sub1/a.ts -> ./main/a.ts

Actually, you cannot tell by ls -l alone. This is because, in most cases, a shared file exists within a parent folder or a grandparent folder... that is itself a symbolic link. You wouldn't know unless you ran ls -l on that specific folder.

$ ls -l ./sub1/a.ts    #// You can't tell just by checking the file
./sub1/a.ts
$ ls -l ./main/a.ts    #// The link destination
./main/a.ts
$ ls -l                #// You only find out after checking the parent folder
./sub1/ -> ./main/

In this article, I will provide a command template that checks the status of parent folders and beyond by just specifying the file path (like ./sub1/a.ts or ./main/a.ts above) to determine if a file is shared. I will also provide a template to list the link sources.

Run the following command in bash (Linux, Windows Git). However, please replace the __FileFullPath__ part with the full path (absolute path) of the file you want to check. You can copy and paste the rest as is.

_path=__FileFullPath__;  echo "$_path";  _link=$(readlink -f "$_path");  echo "$_link";  if [[ "$_path" == "$_link" ]];  then echo "not in link";  else echo "in link";  fi;  unset _path;  unset _link

If it is inside a link, it will display as follows:

in link

If it is not inside a link, it will display as follows:

not in link

For zsh (mac), the command is as follows:

_path=__FileFullPath__;  echo "$_path";  _link=$(python -c "import os,sys;print(os.path.realpath('$_path'))");  echo "$_link";  if [[ "$_path" == "$_link" ]];  then echo "not in link";  else echo "in link";  fi;  unset _path;  unset _link

You can replace __FileFullPath__ with something like $(pwd)/relative.txt to act as a relative path, but you cannot use .. (parent) like $(pwd)/../relative.txt.

Sample

For example, let's create the following folder structure and check if these paths are links:

  • ./main/a.ts (not in link)
  • ./sub1/a.ts (in link)

For bash (Linux), enter the commands as follows:

$ mkdir  try_link
$ cd     try_link
$ mkdir  main
$ echo "a"  >  ./main/a.ts
$ ln -sf  ./main  ./sub1    #// Create a symbolic link
$ ls -l
drwxr-xr-x  user1  group1  12:00 main
lrwxrwxrwx  user1  group1  12:00 sub1 -> ./main

$ _path=$(pwd)/main/a.ts;  echo "$_path";  _link=$(readlink -f "$_path");  echo "$_link";  if [[ "$_path" == "$_link" ]];  then echo "not in link";  else echo "in link";  fi;  unset _path;  unset _link
not in link

$ _path=$(pwd)/sub1/a.ts;  echo "$_path";  _link=$(readlink -f "$_path");  echo "$_link";  if [[ "$_path" == "$_link" ]];  then echo "not in link";  else echo "in link";  fi;  unset _path;  unset _link
in link

$ cd ..
$ rm -rf  try_link

On Windows, installing Git for Windows provides a bash (shell) where you can use the above commands almost as they are.

  • https://git-scm.com/ >> Downloads >> Windows
  • Open the downloaded file (e.g., Git-2.33.0.2-64-bit.exe)
  • Click Next 9 times
  • Configuring the line ending conversions: Checkout as-is, commit as-is
  • Use defaults for other installation options

Regarding the ln -sf command to create symbolic links, open a new Git Bash as an administrator and enter the following command instead.

(In Git Bash opened as an administrator)

cd __ParentOfMakingLink__  #// Folder where the symbolic link is created
MSYS=winsymlinks:nativestrict ln -sf  __Target__  __LinkFileName__

To open Git Bash as an administrator, click the Windows Start button, type "git bash", right-click the Git Bash icon, and select [Run as administrator].

There are methods online describing how to change Group Policy so that you can create symbolic links without being an administrator, but I do not recommend this due to security concerns.

https://docs.microsoft.com/ja-jp/windows/security/threat-protection/security-policy-settings/create-symbolic-links#security-considerations

(Reference) How It Works

If you format the executed command, it looks like this:

_path=__FileFullPath__
_link=$(readlink -f "$_path")
if [[ "$_path" == "$_link" ]]; then
    echo "not in link"
;else
    echo "in link"
;fi;
unset _path;
unset _link

The readlink -f command stores the full path of the link destination in the _link variable. If it is not a symbolic link, the full path of the specified file itself is stored. Therefore, we determine the status by whether the specified full path remains the same or changes. If a relative path is passed to readlink -f, it returns the full path.

Note that we are temporarily defining variables starting with an underscore, such as _link. These are deleted once they are no longer needed. Please be careful, as if a variable with the same name was defined elsewhere, it will be deleted.

While checking whether a file is a symbolic link or a regular file is often sufficient, it may be insufficient from the perspective of whether a file is shared.

This is because even if the file you check is a regular file, if that file is the destination of a symbolic link from somewhere else, the file is shared.

I will introduce a method to find where the file you are checking is linked from (link sources).

For example, if there are 4 links like this:

./main/a.ts
./sub1 -> ./main
./sub2 -> ./other
./sub3 -> ./main
./a.ts -> ./main/a.ts

The link sources for ./main/a.ts are:

  • ./sub1/a.ts
  • ./sub3/a.ts
  • ./a.ts

While we'd like to find those specifically, the method described below lists the symbolic links to the original folders or files.

./sub1 -> ./main
./sub3 -> ./main
./a.ts -> ./main/a.ts

Searching for a file and returning its folder is a bit complicated, but it has the merit that once the origin is known, the overall scope of sharing is also understood.

Preparation

Perform the process of saving the list of symbolic links to a temporary file _links.txt. However, please edit the __Project__ part.

cd  __Project__
find "." -type l -ls | grep -v /node_modules/ | awk '{print $11,$12,$13}' | tee ~/_links.txt
  • Link sources outside of __Project__ will be excluded from the search.
  • grep -v /node_modules/ is a folder to exclude from the search. This is essential for Node.js projects, but entering it for other projects is not an issue.

Write the full path of the link destination file into the ~/_full_path.txt file. Edit the __FullPath__ part below and copy-paste the rest. You can write it as $(pwd)/relative.txt to act as a relative path, but you cannot use .. (parent).

echo "__FullPath__" > ~/_full_path.txt;  cat ~/_full_path.txt

Set the delimiter for the for loop to a newline:

IFS=$'\n'

Main Processing

Search for and list symbolic links where the specified file is included in the link destination. Copy and paste the following directly into the shell.

For bash (Linux, Windows Git):

for  line  in $(cat ~/_links.txt); do
    readlink -f ${line%% *} | xargs -i  grep {}  ~/_full_path.txt > /dev/null && echo "${line%% *} -> ${line##* } ($(readlink -f ${line%% *}))"
done

For zsh (mac):

for  line  in $(cat ~/_links.txt); do
    python -c "import os,sys;print(os.path.realpath('${line%% *}'))" | xargs -I{}  grep {}  ~/_full_path.txt > /dev/null && echo "${line%% *} -> ${line##* } ($(python -c "import os,sys;print(os.path.realpath('${line%% *}'))"))"
done

Cleanup

Restore environment variables and delete temporary files. Copy and paste as is.

unset IFS
rm ~/_full_path.txt
rm ~/_links.txt

Sample

Let's run it and see how it works.

For bash (Linux), enter the commands as follows:

$ mkdir  try_link
$ cd     try_link
$ mkdir  main
$ echo "a"  >  ./main/a.ts
$ ln -sf  ./main  ./sub1    #// Create a symbolic link
$ ln -sf  ./other ./sub2
$ ln -sf  ./main  ./sub3
$ ln -sf  ./main/a.ts  ./a.ts  #// Create a symbolic link (last one)
$ ls -l
lrwxrwxrwx  user1  group1  12:00 a.ts -> ./main/a.ts
drwxr-xr-x  user1  group1  12:00 main
lrwxrwxrwx  user1  group1  12:00 sub1 -> ./main
lrwxrwxrwx  user1  group1  12:00 sub2 -> ./other
lrwxrwxrwx  user1  group1  12:00 sub3 -> ./main

$ cd "."  #// Search scope
$ find "." -type l -ls | grep -v /node_modules/ | awk '{print $11,$12,$13}' | tee ~/_links.txt

$ echo "$(pwd)/main/a.ts" > ~/_full_path.txt;  cat ~/_full_path.txt  #// Link destination
/home/user1/try_link/main/a.ts
$ IFS=$'\n'

$ for  line  in $(cat ~/_links.txt); do
        readlink -f ${line%% *} | xargs -i  grep {}  ~/_full_path.txt > /dev/null && echo "${line%% *} -> ${line##* } ($(readlink -f ${line%% *}))"
    done
./a.ts -> ./main/a.ts (/home/user1/try_link/main/a.ts)
./sub1 -> ./main (/home/user1/try_link/main)
./sub3 -> ./main (/home/user1/try_link/main)

$ unset IFS
$ rm ~/_full_path.txt
$ rm ~/_links.txt

$ cd ..
$ rm -rf  try_link

For bash (Windows Git), create a symbolic link as follows instead of the ln -sf command.

Open Git Bash as an administrator and run:

cd __ParentOfMakingLink__  #// Folder where the symbolic link is created
MSYS=winsymlinks:nativestrict ln -sf  __Target__  __LinkFileName__

Some of you might not find it obvious why it's necessary to check whether something is a symbolic link or a regular file, so I'll list some use cases.

For example, it's common for a program's installation folder to be separated by version, with a symbolic link used to allow execution from a common path.

/usr/bin/program.1.0.0/bin/program  #// Entity
/opt/program/bin/program            #// Launch path

In this case, the symbolic link is created as follows:

/opt/program  ->  /usr/bin/program.1.0.0

If you don't check whether it's a symbolic link, you might install it in a configuration that doesn't separate versions, without realizing that version-specific folders exist.

In another example, if a source file you edited is shared, you should find where the original is located and run the tests near that original as soon as possible. Otherwise, bugs with a wide range of impact might occur later, forcing you to recall the details of the source file you edited previously.

__Projects__/
    __Application__/
        src/main.tx
        src/lib/a.ts  -> __Library__/src/a.ts
    __Library__/
        src/a.ts
        test/a_test.ts

Discussion