Issue
I' trying to write a script in bash. it is a to-do list maker. so the find_tasks
function has a problem that I can't tell. I want to use grep to filter each line based on a pattern/ string.
this is the code:
#! /bin/bash
#initial file for saving tasks to
file=tasks.csv
#adding tasks to the list. 0 is for undone tasks. it is their default value.
function add_tasks {
echo "0,$1,$2" >> "$file"
}
#when it is called it will clear the tasks.csv file
function clear_tasks {
> "$file"
}
#it will show all of the tasks from the tasks.csv file in a formatted way
function list_tasks {
awk -F',' '{print NR" | "$1" | "$2" | "$3}' "$file"
}
#it is for finding a specific task
function find_tasks {
grep -i "$2"
}
#calling the functions
case $1 in
"add")
task_name=$3
if [[ -z $task_name ]]; then
echo "Option -t|--title Needs a Parameter"
exit
fi
priority=$5
if [[ $priority != 'L' && $priority != 'M' && $priority != 'H' ]]; then
echo "Option -p|--priority Only Accept L|M|H"
exit
fi
add_tasks "$task_name" "$priority";;
"clear")
clear_tasks;;
"list")
list_tasks;;
"find")
find_tasks;;
*)
echo "Command Not Supported!"
esac
I have entered four entries to a file named tasks.csv
by using ./todo.sh add -t "First Task" -p H
, ./todo.sh add -t "Second Task" -p M
, ./todo.sh add -t "Third Task" -p H
, and ./todo.sh add -t "Fourth Task" -p L
. now I want to use ./todo.sh find Second
for instance to have the second task like this: 0,Second Task,M
. but it prints out all of the lines from the tasks.csv
file. so what should I do to have the appropriate line from the tasks.csv file based on the string I give to the grep command? what should I change in the find_tasks
function to have the appropriate output?
Solution
You are not passing arguments.
find_tasks;;
^^^ - nothing
Pass the arguments.
find_tasks "$@" ;;
Check your script with shellcheck.
Do not use function name {
. Use name() {
. See here.
Answered By - KamilCuk Answer Checked By - Pedro (WPSolving Volunteer)