minishell/src/minishell.c

72 lines
1.9 KiB
C
Raw Normal View History

2025-02-06 13:44:55 +01:00
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* minishell.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kcolin <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/02/06 13:44:06 by kcolin #+# #+# */
/* Updated: 2025/02/19 17:02:17 by khais ### ########.fr */
2025-02-06 13:44:55 +01:00
/* */
/* ************************************************************************** */
// stdio must be included before readline
#include <stdio.h>
2025-02-06 14:21:01 +01:00
#include <readline/history.h>
#include <readline/readline.h>
2025-02-06 14:21:01 +01:00
#include <stdbool.h>
#include <stdlib.h>
#include <unistd.h>
#include "libft.h"
/*
** remove one '\n' from the end of the string, if it exists
*/
static char *strip_newline(char *str)
{
size_t last_char_idx;
if (str == NULL)
return (NULL);
last_char_idx = ft_strlen(str) - 1;
if (str[last_char_idx] == '\n')
str[last_char_idx] = '\0';
return (str);
}
2025-02-06 14:21:01 +01:00
/*
** get a command line using readline.
**
** returned buffer must be freed by caller.
** will add command to history if appropriate.
*/
static char *get_command(void)
{
char *line;
if (isatty(STDIN_FILENO))
line = readline("$ ");
else
line = strip_newline(get_next_line(STDIN_FILENO));
2025-02-06 14:21:01 +01:00
if (line != NULL && line[0] != '\0')
add_history(line);
return (line);
}
2025-02-06 13:44:55 +01:00
int main(int argc, char *argv[], char **envp)
{
char *line;
2025-02-06 13:44:55 +01:00
(void)argc;
(void)argv;
(void)envp;
2025-02-06 14:21:01 +01:00
line = get_command();
while (line != NULL)
{
ft_printf("%s\n", line);
free(line);
2025-02-06 14:21:01 +01:00
line = get_command();
}
2025-02-06 13:44:55 +01:00
return (0);
}