在Bash中,将整数附加到文件或目录名称以避免重复的有效方法是什么?

时间:2014-11-05 16:27:06

标签: bash variables append

我有一个小功能,可用于将对象移动到垃圾目录:

trash(){
    object="${1}"
    directoryTrashWithTildePrefix="~/trash"
    eval directoryTrash="${directoryTrashWithTildePrefix}"
    if [ -z "${object}" ]; then
        echo "object not specified"
        return
    fi
    # If the trash directory does not exist, create it.
    mkdir -p "${directoryTrash}"
    # Move the object to trash.
    echo "moving "${object}" to "${directoryTrashWithTildePrefix}""
    # Move the object in a way appropriate to its type (file or directory).
    if [ -f "${object}" ]; then
        mv "${object}" "${directoryTrash}"
   elif [ -d "${object}" ]; then
        mv "${object}" "${directoryTrash}"
    else
        echo ""${object}" not file or directory"
        return
    fi
}

是否有一种有效,明智的方法可以自动将整数附加到对象的名称,以避免垃圾邮件目录中出现重复的名称?

1 个答案:

答案 0 :(得分:1)

您可以使用时间戳,例如: myObject的OBJ = _ date +"%Y%m%d_%H%M%S"

[oriz@ lib git:master]$ myObject=obj_`date +"%Y%m%d_%H%M%S"`
[oriz@ lib git:master]$ echo $myObject
obj_20141105_201843
[oriz@ lib git:master]$ myObject=obj_`date +"%Y%m%d_%H%M%S"`
[oriz@ lib git:master]$ echo $myObject
obj_20141105_201847