Search code examples
linuxbashgrepcommand-substitution

'command not found' when passing variable into BASH function, am I quoting incorrectly?


So I have a command that basically adds a line to a file, but only if that line isn't already in the file. It uses grep to check the file and if not there then appends to the file.

The purpose of this is because I want to import all my aliases into BASH from an installation script that is likely to be executed more than once (and I don't want to fill ~/.bashrc with duplicate lines of the same alias).

The command works fine by itself, but when I try to abstract it away into a function to reuse elsewhere, I get the error: command not found.

So far I've looked at grep and pattern matches (thinking maybe & or ~ was throwing it off), parameter expansion OR command expansion and quoting.

I feel it's the latter i.e. I'm not quoting the alias string or file string correctly and it's trying to execute it as a command instead of a string.

I've been pulling my hair out for a while on this one, would somebody please be able to point me in the right direction?

Any help appreciated!

# Command (which works)
grep -qxF 'alias gs="clear && git status"' ~/.bashrc || echo 'alias gs="clear && git status"' >> ~/.bashrc

# Wrap command in function so I can reuse and pass in different parameters
function append_unique_line {
    grep -qxF $1 $2 || echo $1 >> $2
}

# Doesn't work.. append_unique_line: command not found
append_unique_line 'alias gs="clear && git status"' ~/.bashrc

Solution

  • Try

    function append_unique_line() {
        grep -qxF "$1" "$2" || echo "$1" >> "$2"
    }
    
    append_unique_line 'alias gs="clear && git status"' ~/.bashrc
    

    Always wrap your variable in " for expansion.