How to tell whether a file is a symbolic link in shell script All In One

发布时间 2023-10-25 14:28:18作者: xgqfrms

How to tell whether a file is a soft symbolic link in shell script All In One

shell 脚本中如何判断一个文件是否是软链接 / 软符号链接

error

软链接自动指向原文件 bug ❌

# 软链接
$ test ./test.sh -ef ./test-soft-link.sh
$ echo $?
0

# 硬链接 ❌
$ test ./test.sh -ef ./test-hard-link.sh
$ echo $?
0

#!/usr/bin/env bash

# 软链接 bug ❌ 自动指向原文件
echo "./test.sh -ef ./test-soft-link.sh"
# if [ ./test.sh -ef ./test-soft-link.sh ]; then
if [[ ./test.sh -ef ./test-soft-link.sh ]]; then
  echo "yes ✅"
else
  echo "no ❌"
fi

echo "./test.sh -ef ./test-hard-link.sh"
# if [ ./test.sh -ef ./test-hard-link.sh ]; then
if [[ ./test.sh -ef ./test-hard-link.sh ]]; then
  echo "yes ✅"
else
  echo "no ❌"
fi



# 单方括号 [] ✅
echo "[ ./test.sh -ef ./test-demo.sh ]"
if [ ./test.sh -ef ./test-demo.sh ]; then
  echo "yes ✅"
else
  echo "no ❌"
fi

# 双方括号 [[]] ✅
echo "[[ ./test.sh -ef ./test-demo.sh ]]"
if [[ ./test.sh -ef ./test-demo.sh ]]; then
  echo "yes ✅"
else
  echo "no ❌"
fi

solution

# soft symbol link ✅
eric@rpi4b:~ $ [ -L ./test-soft-link.sh ] && [ -e ./test-soft-link.sh ]
eric@rpi4b:~ $ echo $?
0

# hard symbol link ❌
eric@rpi4b:~ $ [ -L ./test-hard-link.sh ] && [ -e ./test-hard-link.sh ]
eric@rpi4b:~ $ echo $?
1

demos

eric@rpi4b:~ $ ls -ali | grep test
 24553 -rw-r--r--  1 eric eric   411  9月 21 11:37 nvm_echo_test.sh
 30221 -rwxr-xr-x  1 eric eric   172  9月 21 18:03 shell-env-variable-test.sh
 30331 -rwxr-xr-x  1 eric eric    47 10月 25 00:26 test-demo.sh
 24592 -rwxr-xr-x  2 eric eric   156  9月 21 13:15 test-hard-link.sh
 24592 -rwxr-xr-x  2 eric eric   156  9月 21 13:15 test.sh
 23662 lrwxrwxrwx  1 eric eric     7 10月  8 16:44 test-soft-link.sh -> test.sh
eric@rpi4b:~ $ test ./test.sh -ef ./test-soft-link.sh
eric@rpi4b:~ $ echo $?
0
eric@rpi4b:~ $ 

image

(? 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs

https://stackoverflow.com/questions/5767062/how-to-check-if-a-symlink-exists



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 ?️,侵权必究⚠️!