我正在尝试创建一个命令,列出目录中每个文件的第一行或最后一行(用户指定的编号),该文件也由用户指定。他们也可以选择使用头部或尾部。
HEADORTAIL=$1
NUMLINES=$2
DIRECTORY=$3
if [ $# -lt 3 ]
then
echo "The command needs three arguments to work"
echo "The usage of this command is as follows: lshead [-head or -tail] [n$
exit
elif [ -d "$DIRECTORY" ]
then
echo "This directory exists"
while [ $2 -lt 1 ] ; do
echo "The number of lines you wish to see must be greater than 0"
read $2
done
if [ $1 == "-head" ]
then
head -$2 $HOME/$3/*
elif [ $1 == "-tail" ]
then
tail -$2 $HOME/$3/*
exit
fi
fi
fi
fi
exit
我真的不知道从终端的答案会有什么期待。如果我犯了任何错误或做了任何愚蠢的事,我会道歉。我相对知道打击shell脚本和本网站。
运行命令时出现此错误。
lshead3 -head 10 bin
./lshead3: line 30: syntax error near unexpected token `fi'
./lshead3: line 30: `fi'
当我把它放入ShellCheck
时就得到了这个$ shellcheck myscript
Line 9:
echo "The usage of this command is as follows: lshead [-head or -tail] [n$
^-- SC1009: The mentioned parser error was in this simple command.
^-- SC1078: Did you forget to close this double quoted string?
Line 11:
elif [ -d "$DIRECTORY" ]
^-- SC1079: This is actually an end quote, but due to next char it looks suspect.
^-- SC1078: Did you forget to close this double quoted string?
Line 13:
echo "This directory exists"
^-- SC1079: This is actually an end quote, but due to next char it looks suspect.
Line 21:
elif [ $1 == "-tail" ]
^-- SC1073: Couldn't parse this double quoted string.
Line 28:
^-- SC1072: Expected end of double quoted string. Fix any mentioned problems and try again.
$
答案 0 :(得分:1)
1 #!/bin/bash
2 head_or_tail=$1
3 num_lines=$2
4 directory=$3
5
6 if [ $# -ne 3 ]
7 then
8 echo "The command needs three arguments to work"
9 echo "The usage of this command is as follows: lshead [head or tail] [numlines] [directory]"
10 exit 1
11 fi
12
13
14 if [[ "$num_lines" -lt 1 ]]
15 then
16 echo "The number of lines you wish to see must be greater than 0"
17 exit 1
18 fi
19
20 if [[ ! -d "$directory" ]]
21 then
22 echo "Directory $directory does not exist"
23 exit 1
24 else
25 echo "looking in directoy $directory"
26 if [[ "$head_or_tail" = "head" ]]
27 then
28 head -n "$num_lines" "$directory"/*
29 elif [[ "$head_or_tail" = "tail" ]]
30 then
31 tail -n "$num_lines" "$directory"/*
32 fi
33 fi
34 exit
注:
第2-4行:将命令行参数存储到变量中,以便向下使用它们,并保持代码可读且易于理解
第6行:使用-ne
代替-lt
。这将确保即使参数数量超过3(不仅少于3),您的脚本也会失败
您不需要在代码中使用read
(阅读read
的手册页),因为您没有从fd
读取行。您需要将参数的值存储在Line:2-4
如果使用while
循环,请确保条件在完成时失败,以便执行突破循环。这样做的方法是使用您未在代码中使用的递增或递减计数器
确保将目录的绝对路径作为第三个参数传递。这样,当您$HOME
或head
tail
使用head
显示n
中的第一个head -n [numlines]
行的正确方法,tail
重要提示:另请阅读下面的Charles Duffy评论,他指出了非常重要的事情,不容错过。
答案 1 :(得分:0)
find [directory] -type f | while read f; do tail -n [num_lines] "$f"; done
类似地,
find [directory] -type f | while read f; do head -n [num_lines] "$f"; done