创建新文件,但添加号码,如果文件名在bash已经存在 [英] Create new file but add number if filename already exists in bash

查看:92
本文介绍了创建新文件,但添加号码,如果文件名在bash已经存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了类似的问题,但不是在Linux的/猛砸

I found similar questions but not in Linux/Bash

我希望我的脚本来创建具有给定名称(通过用户输入)的文件,但在末尾添加号码,如果文件名已经存在。

I want my script to create a file with a given name (via user input) but add number at the end if filename already exists.

例如:

$ create somefile
Created "somefile.ext"
$ create somefile
Created "somefile-2.ext"

感谢您阅读

推荐答案

下面的脚本可以帮你。不应该同时被运行脚本的多个副本,以避免竞态条件

The following script can help you. You should not be running several copies of the script at the same time to avoid race condition.

name=somefile
if [[ -e $name.ext ]] ; then
    i=0
    while [[ -e $name-$i.ext ]] ; do
        let i++
    done
    name=$name-$i
fi
touch $name.ext

这篇关于创建新文件,但添加号码,如果文件名在bash已经存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆