Create new file but add number if filename already exists in bash

前端 未结 8 1562
Happy的楠姐
Happy的楠姐 2020-12-08 09:56

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 ex

8条回答
  •  攒了一身酷
    2020-12-08 10:43

    Try something like this (untested, but you get the idea):

    filename=$1
    
    # If file doesn't exist, create it
    if [[ ! -f $filename ]]; then
        touch $filename
        echo "Created \"$filename\""
        exit 0
    fi
    
    # If file already exists, find a similar filename that is not yet taken
    digit=1
    while true; do
        temp_name=$filename-$digit
        if [[ ! -f $temp_name ]]; then
            touch $temp_name
            echo "Created \"$temp_name\""
            exit 0
        fi
        digit=$(($digit + 1))
    done
    

    Depending on what you're doing, replace the calls to touch with whatever code is needed to create the files that you are working with.

提交回复
热议问题