Home > Software engineering >  Script as a variable value
Script as a variable value

Time:11-19

Can you please explain if it is possible to store the script as a variable? This is the script:

### SCRIPT1 ###

if [ "$4" = "test-1" ] ; then
        existing_user1=$(ldapsearch -x -b "cn=users,cn=servers,ou=servers,dc=com" -H ldap://127.0.0.1 -D "cn=admin,dc=servers,dc=com" -w "pass" cn     uid | grep "uid: $3" | grep -oE '[^ ] $')
        if [ "$existing_user1" = "$3" ] ; then
                exit -1
        elif [ "$existing_user1" = "" ] ; then 
                gid=523 ; cn="cn=users,cn=servers"
        fi

elif [ "$4" = "servers2" ] ; then
        existing_user2=$(ldapsearch -x -b "cn=users,cn=servers,ou=servers,dc=servers,dc=com" -H ldap://127.0.0.1 -D "cn=admin,dc=servers,dc=com" -w "pass" cn uid | grep "uid: $3" | grep -oE '[^ ] $')
        if [ "$existing_user2" = "$3" ] ; then
               (echo "dn: cn=servers,ou=servers,dc=servers,dc=com"
               echo "add: memberUid"
               echo "memberUid: $3") | ldapmodify -D "cn=admin,dc=servers,dc=com" -w "pass"
               exit -1
       elif [ "$existing_user2" = "" ] ; then
               gid=523 ; cn="cn=users,cn=servers"
               (echo "dn: cn=servers,ou=servers,dc=servers,dc=com"
               echo "add: memberUid"
               echo "memberUid: $3") | ldapmodify -D "cn=admin,dc=servers,dc=com" -w "pass"
       fi
fi
)

I tried like this

my_new_variable=( here I pasted the script from above )

But, looks like it is not working properly... I changed brackets with quotation mark, but that that did not work either.

So far I did have some simple stuff as variable value, but nothing complicated like another bash script.

I would like to have the above script set as the variable that I can later in the script inside awk.

Thank you in advance

CodePudding user response:

You should first save it as a file, and then store it into some variable. e.g. var=$(cat script.sh)

CodePudding user response:

You can use a here-document:

script=$(cat <<"EOF"
### SCRIPT 1 ###

# commands

# last line
EOF
)

Everything on the lines in between "EOF" and EOF are passed literally, as cat's standard input. This is nested inside a command substitution, to put it in a variable. The final EOF string must be on it's own line, so the closing ) must go on the next line. Note that any trailing new lines will be stripped, because it's a command substitution.

"EOF" can be any quoted word. If quotes are not used, variables, arithmetic and command subs are expanded.

This syntax is portable to sh, and not bash specific.

  • Related