0

I wanted to get the number of current connections to my postgresql DB. Therefor I'm using this script:

su - postgres -c "psql -c 'SELECT sum(numbackends) FROM pg_stat_database;'"

This is working like a charm. My next step was to modify my .bashrc to use the command cntcon to show the number of connections:

alias cntcon='su - postgres -c "psql -c 'SELECT sum(numbackends) FROM pg_stat_database;'"'

As soon as I want to reload the .bashrc I get follwing error:

-bash: /root/.bashrc: line 16: syntax error near unexpected token `('
-bash: /root/.bashrc: line 16: `alias cntcon='su - postgres -c "psql -c $'SELECT sum(numbackends) FROM pg_stat_database;$'"''

I already found following solution for similar problems on stackoverflow:

-bash: syntax error near unexpected token `)'

Then I got this error:

-bash: alias: -c: not found
-bash: alias: SELECT sum(numbackends) FROM pg_stat_database;: not found

I also tried:

echo "alias cntcon='su - postgres -c "psql -c 'SELECT sum(numbackends) FROM pg_stat_database;'"'" | tee -a .bashrc.
alias cntcon='su - postgres -c psql -c SELECT sum(numbackends) FROM pg_stat_database;'

But got follwoing error:

-bash: alias: sum(numbackends): not found
-bash: alias: FROM: not found
-bash: alias: pg_stat_database: not found
-bash: ": command not found

I assume there is a problem with the several escapes in the script and also I assume that I'm making a simple error.

Thank you in advance!

Community
  • 1
  • 1
Niklas Zantner
  • 182
  • 2
  • 16
  • Single quotes cannot be nested. – tripleee Dec 07 '15 at 19:15
  • `'su` starts a string, and then it ends at `-c 'SELECT`, leaving the rest of the sql unknown/garbage commands as far as bash is concerned. – Marc B Dec 07 '15 at 19:17
  • 1
    [shellcheck](http://www.shellcheck.net) automatically suggests how to [fix this](https://github.com/koalaman/shellcheck/wiki/SC2026). Give it a try. – that other guy Dec 07 '15 at 20:29
  • You wouldn't have this problem if you used a shell function for `cntcon` instead of an alias. – chepner Dec 07 '15 at 20:53

0 Answers0