Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

using grep in a function in ubuntu terminal returns every line of the file instead of the lines that I'm looking for

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading