gpt4 book ai didi

linux - 为什么在运行 bash 脚本时出现意外的文件结束错误?

转载 作者:太空宇宙 更新时间:2023-11-04 09:26:55 24 4
gpt4 key购买 nike

这是我的脚本:

#!/bin/bash
if [ $# -lt 2 || $# -gt 3 ]; then # invalid number of arguments given
echo "usage: minor3 name [euid]"
else # valid number of arguments given
echo Good day, $1! Nice to meet you!
CHOICE=1
while [ "$CHOICE" -gt 0 && "$CHOICE" -lt 4 ] # print out the menu, obtain user choice, execute appropriate system call using if-else statements, loop if desired
do
echo "+*******************************************************************+
Enter one of the following options: |
1) List and count all non-hidden files in the current directory. |
2) Check if given user (default = current user) is logged in, then |
... list all active processes for that user. |
3) List the sizes and names of the 10 largest files and directories |
... in the current directory. |
4) Exit this shell program. |
+*******************************************************************+
> "
read CHOICE
if [ "$CHOICE" = 1 ]; then
# list and count all files
echo test
fi
if [ "$CHOICE" = 2 ]; then
if [ $# = 3 ]; then # euid was given
# use given user ($2)
echo given user
else
# use current user
echo current user
fi
fi
if [ "$CHOICE" = 3 ]; then
# list sizes and names of 10 largest files/directories
echo test
fi
done
echo Thanks, $1! Have a great day!
fi

这是我遇到的错误:

cwd0042@cse04:~/3600/min3$ chmod +x minor3.sh
cwd0042@cse04:~/3600/min3$ ./minor3.sh
./minor3.sh: line 51: syntax error: unexpected end of file

第 51 行是最后一个 fi 之后的行,即我程序的最后一行之后的行。我发现了一个较早的堆栈溢出帖子说使用 dos2unix,但是我必须测试的 Linux 服务器是我学校所有的,所以我没有能力安装它,所以它不是一个选项。服务器使用 Linux Ubuntu 12.04.5 LTS,如果有区别的话。

最佳答案

您不能在 [ ... ] 中使用 &&|| ,它们只会调用test command .

使用 -a-o 代替或使用两个 [...] 表达式:

if [ "$#" -lt 2 ] || [ "$#" -gt 3 ] ; then

另一种方法 是使用内置的 [[ ... ]] bash 运算符。它允许使用 &&||:

if [[ "$#" -lt 2 || "$#" -gt 3 ]]; then

不输入程序也会崩溃一个数字,只需键入 Enter。至少检查如果 $CHOICE 为空。

看起来你有 CRLF 行结尾(类似 dos),使用例如

perl -pi -e 's/\r\n/\n/g' -- YOURSCRIPTNAME.sh

解决这个问题。这模拟了 dos2unix

关于linux - 为什么在运行 bash 脚本时出现意外的文件结束错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35408045/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com