脚本问题 - 使用 IF/THEN 出现意外的文件结尾

1 bash scripts

最终转向 Linux 并决定学习绳索的最佳方法是尝试编写脚本。

尝试制作一个基本的(开始非常基本并不断增长)脚本,根据用户输入自动挂载或卸载分区。以为我走在正确的道路上,但无法弄清楚出了什么问题。如果这只是非常愚蠢的事情,请提前道歉。

#!/bin/bash
# Test script to auto mount hdd based in user input

echo "Do you wish to mount or unmount?"
read origin

if [ $origin == mount ]; then
    echo "Partitions : $(lsblk)"
    echo "Please enter device name e.g. sda1"
    read device
    echo "Please enter dir location e.g. /mnt"
    read location
    mount -t ntfs /dev/$device $location
if [ $origin == unmount ]; then
    echo "Mounts : $(mount)"
    echo "Please enter mount location e.g. /mnt"
    read ulocation
    umount $ulocation
fi
Run Code Online (Sandbox Code Playgroud)

wja*_*rea 6

改变这一行:

if [ $origin == unmount ]; then
Run Code Online (Sandbox Code Playgroud)

对此:

elif [ $origin == unmount ]; then
Run Code Online (Sandbox Code Playgroud)

您收到此错误是因为 bash 将第二个解释if为嵌套,而不是第二个条件。这是一个带有缩进的可视化。

if [ $origin == mount ]; then
  # Do some things.
  if [ $origin == unmount ]; then
    # Do some things.
  fi
#fi
Run Code Online (Sandbox Code Playgroud)

顺便说一句,您还应该引用您的变量以防止分词和通配符:

if [ "$origin" == mount ]; then
    ...
    mount -t ntfs /dev/"$device" "$location"
elif [ "$origin" == unmount ]; then
    ...
    umount "$ulocation"
Run Code Online (Sandbox Code Playgroud)