首页 > 解决方案 > 如果变量声明在bash的for循环内,为什么不能更改输入数据

问题描述

所以我试图制作一个无限循环,创建库。

但文件变量只接受一次输入。

代码:

for (( ; ; ))
do
    file=${1?Error: no input}
    mkdir "$file"
    sleep 1
done

标签: linuxbashubuntu

解决方案


该循环中没有任何内容要求输入。$1由用户在运行脚本时提供一次(甚至在循环开始之前)。在 shell 脚本中请求输入的标准方法是使用read命令。像这样的东西:

while read -p "Enter a directory to create: " file; do
    mkdir "$file"
done

此循环将在收到文件结尾时终止,这意味着用户必须按 Control-D 退出它。如果您想在用户只按返回而不输入任何内容的情况下退出,您可以这样做:

while read -p "Enter a directory to create: " file; do
    if [ -z "$file" ]; then
        echo "Error: no input" >&2
        break    # This exits the while loop
    fi
    mkdir "$file"
done

推荐阅读