我试图在 if 语句中放置一个 if 语句。它似乎一直工作到脚本中最后一个不打印的 echo 命令。
为了测试,我创建了一个与通过提示输入的 $foldername 同名的目录。我在脚本执行期间输入这个。在脚本运行期间,我选择了覆盖目录的选项,这很好用。但是,我很困惑为什么在文件夹被替换后,脚本不会移动到最后一个 echo 语句:
echo "Folder $foldername has now been created"
Run Code Online (Sandbox Code Playgroud)
这没有打印在屏幕上,这表明脚本没有退出 if 语句部分。任何想法为什么?
#!/bin/bash
echo "Please input the folder name you would like to create then press ENTER"
read foldername
if [ -d "/home/location/test_directories/$foldername" ]
then
echo "$foldername already exists"
sleep 2
echo
echo
echo "Do you want to overwrite this folder and start afresh?"
read -p "Type Y overwrite the folder, or N to exit the script" -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]
then
echo "You have chosen to overwrite the folder $foldername"
rm -rf /home/location/test_directories/$foldername; mkdir /home/location/test_directories/$foldername
sleep 2
else
exit
fi
exit
else
mkdir /home/location/test_directories/$foldername
fi
sleep 2
echo "Folder $foldername has now been created"
Run Code Online (Sandbox Code Playgroud)
是的,您可以if
随心所欲地嵌套语句。
正如在问题的评论中指出的那样,您的代码的问题是这两个exit
语句。采取触发其中任何一个的分支将终止脚本。
据我所知,这两个exit
陈述都是多余的,可能会被删除。
您还应该养成双引用用户交给您的任何变量的习惯,例如$foldername
。在这种情况下,能够处理带有空格的文件夹名称。
...或用换行,制表符或其他“领域分隔符”如果已修改IFS
,或者*
,?
,[
如果你启用了那个特殊的外壳,更加extglob
的选项bash
。
归档时间: |
|
查看次数: |
116 次 |
最近记录: |