【问题标题】:Bash script looping after end of fileBash脚本在文件结束后循环
【发布时间】:2015-01-18 00:56:22
【问题描述】:

我的 bash 脚本询问用户他们的名字、姓氏、地址和电话号码,并将用户输入的这些信息写入格式为“firstname.lastname”的文件;但是我想多次重复此操作(我实际上想做类似 do..while 循环的事情,它至少运行一次并询问用户是否要继续创建帐户,但我认为没有办法。 ..而对于 bash 似乎)。因此,当我在终端中执行此 bash 脚本时,它会询问要创建多少个帐户,并且我提供了所有输入,但它只运行一次。我究竟做错了什么?这是我的脚本。

#!bin/bash

echo "How many accounts are you creating?"
read num
echo "Enter first name" 
read fName
echo "Enter last name"
read lName
echo "Enter address"
read add
echo "Enter phone number"
read phn
echo "Enter gender m for male and f for female"
read gender

if [ "$gender" == "m" ]
    then
        sex="male"
elif [ "$gender" == "f" ]
    then 
        sex="female"
else 
    echo"Invalid gender. Restart the script and enter a valid gender"
    exit 0
fi
for (( i = 0; i<=num; i++))
do
    cat > $fName.$lName <<-EOF
        Full Name: $fName $lName
        Address: $add
        Phone number: $phn
        Gender: $gender
    EOF
done

【问题讨论】:

    标签: linux bash loops unix


    【解决方案1】:

    zerobandwidth 的答案是正确的,但作为替代答案,实际上很容易做你最初想做的事情:

    while true; do
        # Your account creation code goes here
    
        echo "Create another account (y/n)?"
        read another
        if [ "$another" != y ]; then
            break
        fi
    done
    

    【讨论】:

    • 对不起,迟到的评论。这次真是万分感谢。我的脚本现在按预期工作。
    【解决方案2】:

    将您的输入代码放入循环中,或将该代码包装在一个函数中并在循环中调用该函数。

    【讨论】:

      猜你喜欢
      • 2021-11-19
      • 1970-01-01
      • 2019-07-31
      • 2014-10-31
      • 2017-12-04
      • 2018-04-14
      • 2013-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多