How does “cat << EOF” work in bash?

前端 未结 9 1232
深忆病人
深忆病人 2020-11-22 12:24

I needed to write a script to enter multi-line input to a program (psql).

After a bit of googling, I found the following syntax works:

c         


        
9条回答
  •  遇见更好的自我
    2020-11-22 13:14

    Worth noting that here docs work in bash loops too. This example shows how-to get the column list of table:

    export postgres_db_name='my_db'
    export table_name='my_table_name'
    
    # start copy 
    while read -r c; do test -z "$c" || echo $table_name.$c , ; done < <(cat << EOF | psql -t -q -d $postgres_db_name -v table_name="${table_name:-}"
    SELECT column_name
    FROM information_schema.columns
    WHERE 1=1
    AND table_schema = 'public'
    AND table_name   =:'table_name'  ;
    EOF
    )
    # stop copy , now paste straight into the bash shell ...
    
    output: 
    my_table_name.guid ,
    my_table_name.id ,
    my_table_name.level ,
    my_table_name.seq ,
    

    or even without the new line

    while read -r c; do test -z "$c" || echo $table_name.$c , | perl -ne 
    's/\n//gm;print' ; done < <(cat << EOF | psql -t -q -d $postgres_db_name -v table_name="${table_name:-}"
     SELECT column_name
     FROM information_schema.columns
     WHERE 1=1
     AND table_schema = 'public'
     AND table_name   =:'table_name'  ;
     EOF
     )
    
     # output: daily_issues.guid ,daily_issues.id ,daily_issues.level ,daily_issues.seq ,daily_issues.prio ,daily_issues.weight ,daily_issues.status ,daily_issues.category ,daily_issues.name ,daily_issues.description ,daily_issues.type ,daily_issues.owner
    

提交回复
热议问题