如果我有这样的带有符号链接的路径:
/this/one/two/three
有没有快速的一行代码可以确定路径中是否有其他段是符号链接?例如,我想检测这,一,二, 或者三上面的例子中是一个符号链接。
一种方法是将包含符号链接的路径与 的输出进行比较readlink -f <path>
。想知道是否有更快的方法。
答案1
我会用:
if [[ "$my_path" != "$(realpath --canonicalize-existing $my_path)" ]];then
echo The path $my_path is relative path or contains symlinks.
else
echo The path $my_path is absolute.
fi
答案2
您可以在这种情况下或其他情况下使用awk
和print
使用,它非常简单和有用。在这种情况下,您可以执行以下步骤:1 =打开〜/ .bashrc并在该文件末尾添加以下命令
alias issymlink="sh /bin/issymlink.sh $1"
2 = 创建一个包含以下内容的文件/bin/issymlink.sh
#!/bin/bash
path=$1
type=`stat $1 | awk 'FNR == 2 {print $8;}'`
if [ $type != "symbolic" ]
then
echo The path $1 is absolute and type of this path is $type
else
echo The path $1 is symlinks.
fi
3 - 注销并登录或输入su
终端并输入最后你可以输入issymlink PATH/TO/FILE/OR/DIRECTORY
终端并输入来检查文件类型
示例用法和输出:
issymlink /lib
The path /lib is absolute and type of this path is directory
issymlink /etc/nginx/sites-enabled/default
The path /etc/nginx/sites-enabled/default is symlinks.
答案3
我们看到了什么?[[ -L ]]
——为我们完成这项工作。干杯。
# cat script.sh
#!/bin/bash
/bin/rm -vfr this
/bin/mkdir -vp this/one/two/three
/bin/mv -v this/one/two/three this/one/two/real_three
/bin/ln -vfs real_three this/one/two/three
/bin/ls -altr this/one/two/
/bin/mv -v this/one/two this/one/real_two
/bin/ln -vfs real_two this/one/two
/bin/ls -altr this/one/two/
/bin/ls -altr this/one/
tmp="this/one/two/three"
while [ "$tmp" != "." ]; do
if [ -L "$tmp" ]; then
/bin/echo "$tmp - is symlink."
else
/bin/echo "$tmp - is not symlink."
fi
tmp=$(/bin/dirname $tmp)
done
用法:
# bash script.sh
removed 'this/one/two'
removed directory 'this/one/real_two/real_three'
removed 'this/one/real_two/three'
removed directory 'this/one/real_two'
removed directory 'this/one'
removed directory 'this'
/bin/mkdir: created directory 'this'
/bin/mkdir: created directory 'this/one'
/bin/mkdir: created directory 'this/one/two'
/bin/mkdir: created directory 'this/one/two/three'
renamed 'this/one/two/three' -> 'this/one/two/real_three'
'this/one/two/three' -> 'real_three'
total 12
drwxr-xr-x 2 root root 4096 Aug 8 20:08 real_three
drwxr-xr-x 3 root root 4096 Aug 8 20:08 ..
lrwxrwxrwx 1 root root 10 Aug 8 20:08 three -> real_three
drwxr-xr-x 3 root root 4096 Aug 8 20:08 .
renamed 'this/one/two' -> 'this/one/real_two'
'this/one/two' -> 'real_two'
total 12
drwxr-xr-x 2 root root 4096 Aug 8 20:08 real_three
lrwxrwxrwx 1 root root 10 Aug 8 20:08 three -> real_three
drwxr-xr-x 3 root root 4096 Aug 8 20:08 .
drwxr-xr-x 3 root root 4096 Aug 8 20:08 ..
total 12
drwxr-xr-x 3 root root 4096 Aug 8 20:08 ..
drwxr-xr-x 3 root root 4096 Aug 8 20:08 real_two
lrwxrwxrwx 1 root root 8 Aug 8 20:08 two -> real_two
drwxr-xr-x 3 root root 4096 Aug 8 20:08 .
this/one/two/three - is symlink.
this/one/two - is symlink.
this/one - is not symlink.
this - is not symlink.