简体   繁体   English

While循环测试bash脚本中是否存在文件

[英]While loop to test if a file exists in bash script

I am trying to create a loop to prompt the user to create a file.我正在尝试创建一个循环来提示用户创建文件。 If the file already exists, it will keep prompting the user until the user enters a file that does not exist.如果文件已经存在,它会一直提示用户,直到用户输入一个不存在的文件。 But can't seem to get it to work, anyone can help, please?但似乎无法让它工作,有人可以帮忙吗?

file3=/root/simulate/$filename
while true ; do
    if [ ! -f "$file3" ]; then
        read -p "Please enter a file name to create in simulate folder:" filename
        touch /root/simulate/$filename
    elif [ -f "$file3" ]; then
        read -p "Please enter a different file name as $filename already exist:" filename
        touch /root/simulate/$filename
        break
    else
        touch /root/simulate/$filename
    fi
done        

filename variable is empty.文件名变量为空。

There are two way to fill in filename variable有两种方式填写文件名变量

  1. filename variable can pass on shell script by export command.文件名变量可以通过导出命令传递 shell 脚本。 ex) $export filename=newFile if you execute shell script, shell is forking and execute new shell. ex) $export filename=newFile 如果您执行 shell 脚本,shell 正在分叉并执行新的 shell。 new shell taken your mother shell's Environment variables new shell 带走了你母壳的环境变量

  2. Push filename variable into shell script.将文件名变量推送到 shell 脚本中。

note: I picked second way and I changed path of $file3.注意:我选择了第二种方式,并更改了 $file3 的路径。

I fixed codes in block of elif to ask again if something goes wrong.我修复了 elif 块中的代码,以再次询问是否出现问题。

this is a code.这是一个代码。

#!/bin/bash
filename=newFile
file3="./$filename"

while true ; do
    if [ ! -f "$file3" ]; then
        read -p "Please enter a file name to create in simulate folder:" filename
        touch ./$filename
        break
    elif [ -f "$file3" ]; then
        while true ; do
            read -p "Please enter a different file name as $filename already exist:" filename

            if [ ! -f "$filename" ]; then
                touch ./$filename
                break 2
            fi
        done
    else
        touch ./$filename
    fi
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM