Dan Dan - 5 months ago 20
Bash Question

Getting [: too many arguments

I keep getting a runtime error saying [: too many arguments.

Here's my code

Variables

mem_list=/root/Desktop/Dan/List/list.txt
word=[user inputs some word]


The code:

if [ -f "$mem_list" -a grep "$word" "$mem_list" ]
then
echo "word already exists in list"
else
echo "word does not exist yet"
fi


Keep getting [: too many arguments!!

Help me kindly please!

Answer

To run a command, use cmd. Not [ cmd ].

/bin/[ is just another command like grep, and if will check the exit status:

if [ -f "$mem_list" ] && grep -q "$word" "$mem_list"
then
    echo "word already exists in list"
else
    echo "word does not exist yet"
fi