Native alternative for readlink on Windows

前端 未结 2 2142
野的像风
野的像风 2021-02-14 06:28

Windows native alternative for ln -s is mklink.

Is there any native alternative for readlink? Or how to natively

2条回答
  •  孤城傲影
    2021-02-14 07:08

    I don't believe there's any tool directly equivalent to readlink. But you can see in the output of dir whether an item is a symlink or not, so you can still determine this from the command line or in a script.

    Test whether it's a symlink or not

    You can pretty easily test whether a given file is a symlink using syntax like:

     dir mysymlink  | find "" >NUL
     if not errorlevel 1  echo. It's a symlink!
    

    Errorlevel will be 0 in the case that "" is found, and will be 1 otherwise.

    Determine the target of a symlink

    Determining the actual target of the symlink is another matter, and in my opinion not as straight-forward. The output of dir mysymlink | find "" might look like

    11/13/2012  12:53 AM          mysymlink [C:\Windows\Temp\somefile.txt]
    

    You can parse this, but some of the characters make it difficult to deal with all in one variable, so I found it easier to deal with a temporary file:

     dir mysymlink | find "" > temp.txt
     for /f "tokens=6" %i in (temp.txt) do @echo %i
    

    This yields output like [C:\Windows\Temp\somefile.txt]. (Remember to use %%i within any batch scripts; the above is from the command prompt.)

    To get the result without the brackets, you can do something like:

     dir mysymlink | find "" > temp.txt
     for /f "tokens=6" %i in (temp.txt) do set answer=%i
     echo %answer:~1,-1%
    

    The variable %answer% contains the result with the brackets, so %answer:~1,-1% is the result without the first or the last character.

提交回复
热议问题