Best practice is to have the shell do the quoting for you, instead of trying to do it yourself.
In bash, the ideal way to do this is with printf -v varname '%q ' command with args...
, which puts a string which will run your command into varname
.
#!/bin/bash
cmd=( hdbsql -CQajx -U DEFAULT "select entry_id, entry_type_name, utc_start_time, utc_end_time, state_name, message from M_BACKUP_CATALOG where entry_type_name = 'complete data backup' order by backup_id" )
printf -v cmd_q '%q ' "${cmd[@]}"
su - nfoadm -c "$cmd"
If you don't have bash, printf
can be used inside a command substitution; ksh93 will optimize this to avoid the usual fork costs that command substitutions entail.
#!/bin/ksh
cmd=( hdbsql -CQajx -U DEFAULT "select entry_id, entry_type_name, utc_start_time, utc_end_time, state_name, message from M_BACKUP_CATALOG where entry_type_name = 'complete data backup' order by backup_id" )
cmd_q=$(printf '%q ' "${cmd[@]}")
su - nfoadm -c "$cmd"
If you need to work a shell having no non-POSIX extensions, consider using sudo
instead of su
:
#!/bin/sh
sudo -u nfoadm hdbsql -CQajx -U DEFAULT "select entry_id, entry_type_name, utc_start_time, utc_end_time, state_name, message from M_BACKUP_CATALOG where entry_type_name = 'complete data backup' order by backup_id"