0

I am with CentOS 7 and I want to bind an alias to launch PostgreSQL shell(psql). I defined this alias and append it in /etc/profile.d/alias:

alias psql-local="read -p \"PSQL: enter the DB to connect: \" db ; sudo -i -u postgres psql --dbname $db"

It is executable by root.

And, I login as root, and run alias, I get:

alias psql-local='read -p "PSQL: enter the DB to connect: " db ; sudo -i -u postgres psql --dbname '

Note here $db at the end is empty.

Then I run psql-local, but I get error:

[root@lucas_vm ~]
> psql-local
PSQL: enter the DB to connect: jfps
psql: option '--dbname' requires an argument
Try "psql --help" for more information.

Then I enter /etc/profile.d/, and run alias.sh manually, then suddenly I can use this alias:

[root@lucas_vm /etc/profile.d]
> . alias.sh
[root@lucas_vm /etc/profile.d]
> psql-local
PSQL: enter the DB to connect: jfps
psql (10.5)
Type "help" for help.

jfps=#

If I exit psql and run alias again, I see this line changed:

alias psql-local='read -p "PSQL: enter the DB to connect: " db ; sudo -i -u postgres psql --dbname jfps'

Note $db is changed to jfps.

Then, I try to access another database, and it works again.

But, when I exit and alias, I see the --dbname jfps, not the name of second database. When I echo $db, it, instead, is the name of the second db.

Why?

2

Because you're using double-quotes ("..."), the $db variable will be expanded when you define the alias, not when it's used. Try this instead:

alias psql-local='read -p "PSQL: enter the DB to connect: " db ; sudo -i -u postgres psql --dbname "$db"'
  • Um.. it improves: when login and alias, I see: alias psql-local='read -p \"PSQL: enter the DB to connect: \" db ; sudo -i -u postgres psql --dbname "$db"', but when I use it, I see error: > psql-local \n "PSQL:jfps \n -bash: read: `connect:': not a valid identifier \n psql: option '--dbname' requires an argument \n Try "psql --help" for more information. Seems the script is truncated due to single quotes. – WesternGun Feb 1 at 9:33
  • I also tried: 1) single quote $db; 2) escape " and double quote $db 3) double quote $db without escaping. But no avail. – WesternGun Feb 1 at 9:40
  • try prepending a printf "{%s} " before sudo ... and tell me the output you're getting. – pizdelect Feb 1 at 9:42
  • OK so I changed back to your solution (single quote all) and add what you said, and I got same error as before, but with extra {}. Seems empty {%s}. – WesternGun Feb 1 at 9:46
  • 1
    The best thing is to use set -x and the printf "{%s} " ... trick when in doubt. Anyways, variables ($x) and other $ expansions are performed inside double quotes ("...") but not inside single quotes ('...'). – pizdelect Feb 1 at 10:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.