Skip to content

Commit 2cdc7da

Browse files
committed
fix(finsh): Fix crash in 'tail' command with insufficient '-n' arguments
1 parent 583d7f4 commit 2cdc7da

File tree

1 file changed

+29
-5
lines changed

1 file changed

+29
-5
lines changed

components/finsh/msh_file.c

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright (c) 2006-2023, RT-Thread Development Team
2+
* Copyright (c) 2006-2025 RT-Thread Development Team
33
*
44
* SPDX-License-Identifier: Apache-2.0
55
*
@@ -738,6 +738,18 @@ static int cmd_echo(int argc, char **argv)
738738
}
739739
MSH_CMD_EXPORT_ALIAS(cmd_echo, echo, echo string to file);
740740

741+
/**
742+
* @brief Print the last part of a file (tail command).
743+
*
744+
* @note Supported Usage:
745+
* 1. tail <file> : Print last 10 lines.
746+
* 2. tail -n <num> <file> : Print last <num> lines.
747+
* 3. tail -n +<num> <file> : Print starting from line <num>.
748+
*
749+
* @param argc Argument count
750+
* @param argv Argument vector
751+
* @return 0 on success, -1 on failure
752+
*/
741753
static int cmd_tail(int argc, char **argv)
742754
{
743755
int fd;
@@ -751,7 +763,7 @@ static int cmd_tail(int argc, char **argv)
751763

752764
if (argc < 2)
753765
{
754-
rt_kprintf("Usage: tail [-n numbers] <filename>\n");
766+
rt_kprintf("Usage: tail [-n [+]numbers] <filename>\n");
755767
return -1;
756768
}
757769
else if (argc == 2)
@@ -761,19 +773,31 @@ static int cmd_tail(int argc, char **argv)
761773
}
762774
else if (rt_strcmp(argv[1], "-n") == 0)
763775
{
776+
/*
777+
* Check if enough arguments are provided to avoid crash.
778+
* The command requires: "tail" + "-n" + "number" + "file" = 4 args.
779+
*/
780+
if (argc < 4)
781+
{
782+
rt_kprintf("Error: Missing arguments.\n");
783+
rt_kprintf("Usage: tail -n [+]numbers <filename>\n");
784+
return -1;
785+
}
786+
787+
/* Check for explicit start line syntax (e.g., +100) */
764788
if (argv[2][0] != '+')
765789
{
766790
required_lines = atoi(argv[2]);
767791
}
768792
else
769793
{
770-
start_line = atoi(&argv[2][1]); /* eg: +100, to get the 100 */
794+
start_line = atoi(&argv[2][1]); /* eg: +100, skip '+' to get 100 */
771795
}
772796
file_name = argv[3];
773797
}
774798
else
775799
{
776-
rt_kprintf("Usage: tail [-n numbers] <filename>\n");
800+
rt_kprintf("Usage: tail [-n [+]numbers] <filename>\n");
777801
return -1;
778802
}
779803

@@ -839,7 +863,7 @@ static int cmd_tail(int argc, char **argv)
839863
close(fd);
840864
return 0;
841865
}
842-
MSH_CMD_EXPORT_ALIAS(cmd_tail, tail, print the last N - lines data of the given file);
866+
MSH_CMD_EXPORT_ALIAS(cmd_tail, tail, Print the last N lines. Usage: tail -n [+]numbers <filename>);
843867

844868
#ifdef RT_USING_DFS_V2
845869

0 commit comments

Comments
 (0)