Bash script - Using spaces as string

I'm trying to build a really simple TODO list with a bash script. It should allow user to add and remove a task and also see the entire list. I've done it with the following script. But I've issues allowing a given task to take a whitespace as a string. For instance, if I'm adding a task with the command: ./programme_stack.sh add 1 start projet n1, it will only add a task with "start". I've read a couple of things online, I know, I should double quote the variables but after trying this, it doesn't work. I must be missing something on the road.

Here is my script:

#!/bin/bash

TACHES=$HOME/.todo_list
# functions
function remove() {
    res_remove=$(sed -n "$1p" $TACHES)
    sed -i "$1d" $TACHES
}

function list() {
    nl $TACHES
}

function add() {
    if [ ""$(($(wc -l $TACHES | cut -d " " -f 1) + 1))"" == "$1" ]
    then
        echo "- $2" >> $TACHES
    else
        sed -i "$1i - $2" $TACHES
    fi
    echo "Task \"$2\" has been add to the index $1"
}

function isNumber() {
    re='^[0-9]+$'
    if ! [[ $@ =~ $re ]] ; then
        res_isNumber=true
    else
        res_isNumber=false
    fi
}

# application
case $1 in 
    list)
        list
        ;;
    done)
        shift
        isNumber $@
        if ! [[ "$res_isNumber" = false ]] ; then
            echo "done must be followed by an index number"
        else
            nb_taches=$(wc -l $TACHES | cut -d " " -f 1)
            if [ "$1" -ge 1 ] && [ "$1" -le $nb_taches ]; then
                remove $1
                echo "Well done! Task $i ($res_remove) is completed"
            else
                echo "this task doesn't exists"
            fi        
        fi
        ;;
    add)
        shift
        isNumber $1
        if ! [[ "$res_isNumber" = false ]] ; then
            echo "add must be followed by an index number"
        else
            index_max=$(($(wc -l $TACHES | cut -d " " -f 1) + 1))
            if [ "$1" -ge 1 ] && [ "$1" -le $index_max ]; then
                add $1 $2
            else
                echo "Idex must be between 1 and $index_max"
            fi        
        fi
        ;;
    *)
        echo "./programme_stack.sh (list|add|done) [args]"
        ;;
esac

Can you guys see what I'm missing? Many thanks!!

Upvotes: 2

Views: 64

Answers (1)

dash-o
dash-o

Reputation: 14491

To get the script to support embedded spaces, 2 changes are needed 1) Accept embedded space - either 1A) Pass in the task name in quote script add nnn "say hello", OR 1B) Concatenate all the input parameters into single string. 2) Quote the task name to prevent it from being broken into individual words

In the code, implement 1B and 2

add)
   ...
 if [ "$1" -ge 1 ] && [ "$1" -le $index_max ]; then
    num=$1
    shift
    # Combine all remaining arguments
    todo="$@"
    add "$num" "$todo"
 ...

Upvotes: 1

Related Questions