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
# test commnad
$ man test
#!/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
solutions
# stat commnad
$ man stat
# stat
if [ "$(stat -c %h -- "$file")" -gt 1 ]; then
echo "File has more than one name."
fi
# check if shell script is a symlink
if [[ -L "$HOME/test-soft-link.sh" ]]; then
echo "It's a soft link ✅"
else
echo "It's not a soft link ❌"
fi
if [[ -L /home/eric/test-soft-link.sh ]]; then
echo "It's a soft link ✅"
else
echo "It's not a soft link ❌"
fi
if [[ -L "$HOME/test-hard-link.sh" ]]; then
echo "It's a soft link ✅"
else
echo "It's not a soft link ❌"
fi
if [[ -L /home/eric/test-hard-link.sh ]]; then
echo "It's a soft link ✅"
else
echo "It's not a soft link ❌"
fi
eric@rpi4b:~ $ echo $HOME
/home/eric
eric@rpi4b:~ $ pwd
/home/eric
# /home/eric/test-hard-link.sh
# 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:~ $