Combine SQL and YSQLSH Meta-commands on the Command Line Jim KnicelyFebruary 5, 2023 The YugabyteDB SQL shell (ysqlsh) provides a CLI for interacting with YugabyteDB using YSQL The -c flag pecifies that ysqlsh is to execute the given command string, where the command can be a meta-command or some SQL statement. Example: [root@localhost ~]# ysqlsh -U yugabyte -c "\d t;" Table "public.t" Column | Type | Collation | Nullable | Default --------+-------------------+-----------+----------+--------- c1 | integer | | not null | c2 | character varying | | | Indexes: "t_pkey" PRIMARY KEY, lsm (c1 HASH) [root@localhost ~]# ysqlsh -U yugabyte -c "SELECT * FROM t;" c1 | c2 ----+---- 1 | A 2 | B 3 | C (3 rows) Unfortunatley we cannot combine meta-commands and SQL in one command string. [root@localhost ~]# ysqlsh -h -U yugabyte -c "\d t; \x; SELECT * FROM t;" Table "public.t" Column | Type | Collation | Nullable | Default --------+-------------------+-----------+----------+--------- c1 | integer | | not null | c2 | character varying | | | Indexes: "t_pkey" PRIMARY KEY, lsm (c1 HASH) Note that only the first meta-command was executed. One option to get around this limitation is to pipe the command string into ysqlsh, using the \\ meta-command separator. Example: [root@localhost ~]# echo '\d t \\ \x \\ SELECT * FROM t;' | ysqlsh -U yugabyte Table "public.t" Column | Type | Collation | Nullable | Default --------+-------------------+-----------+----------+--------- c1 | integer | | not null | c2 | character varying | | | Indexes: "t_pkey" PRIMARY KEY, lsm (c1 HASH) Expanded display is on. -[ RECORD 1 ] c1 | 1 c2 | A -[ RECORD 2 ] c1 | 2 c2 | B -[ RECORD 3 ] c1 | 3 c2 | C The other option is use multiple -c flags, passing in each command separately. Example: [root@localhost ~]# ysqlsh -U yugabyte -c "\d t;" -c "\x" -c "SELECT * FROM t;" Table "public.t" Column | Type | Collation | Nullable | Default --------+-------------------+-----------+----------+--------- c1 | integer | | not null | c2 | character varying | | | Indexes: "t_pkey" PRIMARY KEY, lsm (c1 HASH) Expanded display is on. -[ RECORD 1 ] c1 | 1 c2 | A -[ RECORD 2 ] c1 | 2 c2 | B -[ RECORD 3 ] c1 | 3 c2 | C Have Fun! Anna Maria City Pier Anna Maria, FL