从变量的末尾删除'/' - bash

时间:2017-03-10 01:28:23

标签: bash

我想从变量的末尾删除'/',以便检查文件是否是目录的符号链接。我已经尝试过几乎所有我能想到或在网上找到的方法,有什么我想念的吗?

如果我检查文件是否是末尾带有'/'的符号链接,则会将其视为目录。这可以通过运行:

来检查
if [ -L symtest/ ] ; then echo "symlink"; fi

其中symtest是目录的符号链接。上面没有输出任何内容。

当我删除'/'时,它工作正常并输出“symlink”:

if [ -L symtest ] ; then echo "symlink"; fi

我的问题是,当它作为变量传递给函数时,有没有办法从名称中删除'/'?

该功能看起来像:

function is_it_a_symlink() {
    if [ -L $1 ] ; then
        echo "This file is a symlink!"
    else
        echo "This file is not a symlink!"
    fi
}

提前致谢。

1 个答案:

答案 0 :(得分:3)

POSIX-ly,使用参数扩展来摆脱最后的/

${parameter%/}

所以,你的情况:

[ -L "${1%/}" ]

外部工具,sed

sed 's_/$__' <<<"$1"

所以:

[ -L "$(sed 's_/$__' <<<"$1")" ]

同样,awk

awk '{sub("/$", "")} 1' <<<"$1"

所以:

[ -L "$(awk '{sub("/$", "")} 1' <<<"$1")" ]
相关问题