最后我决定进入 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
答案1
更改此行:
if [ $origin == unmount ]; then
更改为:
elif [ $origin == unmount ]; then
您之所以会收到此错误,是因为 bash 将第二个解释if
为嵌套,而不是第二个条件。以下是带有缩进的可视化。
if [ $origin == mount ]; then
# Do some things.
if [ $origin == unmount ]; then
# Do some things.
fi
#fi
顺便说一句,您还应该引用您的变量以防止单词拆分和通配符:
if [ "$origin" == mount ]; then
...
mount -t ntfs /dev/"$device" "$location"
elif [ "$origin" == unmount ]; then
...
umount "$ulocation"
答案2
wjandrea 似乎已经涵盖了这些if
问题。我建议发表以下case
声明:
#!/bin/bash
# Test script to auto mount hdd based in user input
while read -rp "Do you wish to mount or unmount? " origin
do
case "$origin" in
m*)
echo "Partitions : $(lsblk)"
read -rp "Please enter device name e.g. sda1: " device
read -rp "Please enter dir location e.g. /mnt: " location
mount "/dev/$device" "$location"
break
;;
u*)
echo "Mounts : $(mount)"
read -rp "Please enter mount location e.g. /mnt: " ulocation
umount "$ulocation"
break
;;
*)
echo "You typed nonsense. Please try again."
;;
esac
done
这样,用户只需输入mount
或mo
,甚至只需 ,即可请求挂载m
。同样,也可以请求卸载,只需输入 ,答案可以简短得多u
。(如果您愿意,可以更加严格。)此外,如果用户未能给出可接受的答案,则会受到斥责并再次询问。
除非您想要进行单词拆分和路径名扩展,否则所有 shell 变量都应如上所示放在双引号中。
另外,为了更大的灵活性,我省略了该-t ntfs
选项。 mount
通常可以自动选择正确的类型。
case
与花哨的 bash 模式匹配相比,使用语句进行模式匹配的优点在于[[...]]
它case
是 POSIX,因此可以移植。