首页 > 解决方案 > Bash - 使用用户输入打破 while 循环

问题描述

我是 linux 的初学者。

我发现我的问题可能已经被解决了,但我无法将答案转移到我的示例中。

我正在尝试制作要求用户提供文件夹名称的脚本,然后创建目录。之后,bash 询问用户是否要创建下一个文件夹,如果答案与“是”不同,则 while 循环应该中断。

我感谢任何形式的帮助。先感谢您。我的代码:https ://pastebin.com/xKNgV9gg

#!/bin/bash
echo 'Welcome in folder generator'
echo '#################################################'
echo '#################################################'

new_directory="yes"

while [ "$new_directory"=="yes" ]
do
    echo 'Give me folder name'
    read folderName
    mkdir $folderName
    echo "Would you like to create next folder ?"
    read $new_directory
done

标签: linuxbash

解决方案


  1. Bash is whitespace (spaces, tabs, newlines) separated.
  2. [ a = b ] is not equal to [ a=b ]. The first compares string 'a' with string 'b', the second check if the string 'a=b' has non-zero length.
  3. Always quote your variables, unless you know you don't have to.
  4. Bash uses single = for string comparision. Double == is supported, but is not standard.
  5. A good read can be found in this thread.

#!/bin/bash
echo 'Welcome in folder generator'
echo '#################################################'
echo '#################################################'

new_directory="yes"

while [ "$new_directory" == "yes" ]
do
    echo 'Give me folder name'
    read folderName
    mkdir "$folderName"
    echo "Would you like to create next folder ?"
    read new_directory
done

推荐阅读