重命名shell脚本中的符号链接

时间:2012-10-21 17:20:29

标签: symlink bash4

假设我有3个符号链接(指向不同的部署版本文件)。

A -> K
B -> L
C -> M

当我进行新部署(称为H)时,我希望最终结果如下:

A -> H
B -> K
C -> L

我所拥有的唯一信息是A,B和C的名称,以及H的名称.K,L,M的名称不为我所知,但可以通过符号链接找到。

我如何在bash shell中创建一个针对我的脚本?

(注意:A,B,C是使用ln -s创建的符号链接)

1 个答案:

答案 0 :(得分:1)

我不明白为什么你需要知道旧的文件名..除非你需要删除它。我写得很快,看起来很好。它不需要旧的已发布文件名。

!/bin/bash
remove_old()
    {
            rm -f "$1"
    }
make_new()
    {
            ln -s "$1" "$2"
    }

if [ $# -ne 3 ]; then
    {
        echo "Nope, you need to provide..."
        echo "(1) link/file name to be removed."
        echo "(2) link/file name to be created"
        echo "(3) the actual file location for #2"      
    }   
    elif [ ! -f "${3}" ]; then
    {
        echo "Sorry, your target ${3} doesn’t exist or is not accessible"
    }
    elif [ -f ${2} ]; then
    {
        echo "Sorry, the new file already exists...want me to remove it?"
        read remove
        if [ "$remove" = "Y" ]||[ "$remove" = "y"]; then
            {
                rm -f "$2"
                remove_old $1
                make_new    $3 $2   
            }
            else
            {
                exit
            }
        fi               
    }
    else
    {
        remove_old $1
        make_new $3 $2
    }
    fi

这是调试输出......

bash -xv autolinker.sh my_link my_new_link test_2/test_file 
#!/bin/bash
remove_old()
    {
            rm -f "$1"
    }
make_new()
    {
            ln -s "$1" "$2"
    }

if [ $# -ne 3 ]; then
    {
        echo "Nope, you need to provide..."
        echo "(1) link/file name to be removed."
        echo "(2) link/file name to be created"
        echo "(3) the actual file location for #2"      
    }   
    elif [ ! -f "${3}" ]; then
    {
        echo "Sorry, your target ${3} doesn’t exist or is not accessible"
    }
    elif [ -f ${2} ]; then
    {
        echo "Sorry, the new file already exists...want me to remove it?"
        read remove
        if [ "$remove" = "Y" ]||[ "$remove" = "y"]; then
            {
                rm -f "$2"
                remove_old $1
                make_new    $3 $2   
            }
            else
            {
                exit
            }
        fi               
    }
    else
    {
        remove_old $1
        make_new $3 $2
    }
    fi
+ '[' 3 -ne 3 ']'
+ '[' '!' -f test_2/test_file ']'
+ '[' -f my_new_link ']'
+ echo 'Sorry, the new file already exists...want me to remove it?'
Sorry, the new file already exists...want me to remove it?
+ read remove
Y
+ '[' Y = Y ']'
+ rm -f my_new_link
+ remove_old my_link
+ rm -f my_link
+ make_new test_2/test_file my_new_link
+ ln -s test_2/test_file my_new_link