简体   繁体   中英

Shell script and sed commands

I have a shell script where I am executing a SQL query like so -

query=$(cat <<all
SELECT
    provider_rendering_npi
INTO table
FROM service sl
WHERE bucket = 'bucket'
AND month_id >= (SELECT month FROM annual);
all
)

sql=$(echo $query | sed -e "s/bucket/$bucket_name/g ; s/table/$directory/g")

psql -h server -U user db -c "$sql"

Based on a condition, I would like to modify the query variable. For example, if the $bucket_name contains no_inp , I would like to modify query to be

query=$(cat <<all
SELECT
    provider_rendering_npi
INTO table
FROM service sl
WHERE bucket = 'bucket'
AND month_id >= (SELECT month FROM annual)
AND st_info = 'no_inp';
all
)

Is there a way to do this without duplicating code?

Create a function parameterized on the optional query expression ( expr ):

query() {
  local expr=$1
  local newline=$'\n';
  cat <<EOF
SELECT
    provider_rendering_npi
INTO table
FROM service sl
WHERE bucket = 'bucket'
AND month_id >= (SELECT month FROM annual)${expr:+$newline}$1
EOF
}

query
query "AND st_info = 'no_inp'"

It's usually easier to assemble things from parts instead patching a whole.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM