ManinGreen ManinGreen - 1 month ago 4
Bash Question

Use value of some variables of parent bash script in new bash script being created by parent

I am trying to create a new bash script (with some commands and variables), from another bash script but the issue is that there are some variable specific to new script that I need as well as I need to use the variable's values of parent script, for now only a new bash script is being created but values of parent scripts aren't copied instead whole variable is being copied.

# commnads ...... xyz for parent script

PATH="this/path/I/want/in/new/script"

echo "#### Setting up post-receive hooks ####"

cd hooks

cat >post-receive << 'EOF'
#!/bin/sh
read oldrev newrev ref

branchname=${ref#refs/heads/}

# the path is actually for first script, how I can get the value for PATH only
GIT_WORK_TREE=$PATH git checkout ${branchname} -f
EOF
chmod +x post-receive


here is the file being created,

#!/bin/sh
read oldrev newrev ref

branchname=${ref#refs/heads/}

GIT_WORK_TREE=$PATH git checkout ${branchname} -f
#^ i need the actual value here not the variable

Answer

You quoted the here document delimiter, so you disabled all parameter expansions, including $PATH. If you want to expand any parameters, you'll have to leave the delimiter unquoted and explicitly escape the $ for the ones you don't want expanded.

Since you don't actually want to override your PATH, don't use PATH as the variable name; use a lowercase name.

path="this/path/I/want/in/new/script"

echo "#### Setting up post-receive hooks ####"

cd hooks

cat >post-receive <<EOF
#!/bin/sh
read oldrev newrev ref

branchname=\${ref#refs/heads/}

GIT_WORK_TREE=$path git checkout \${branchname} -f
EOF
chmod +x post-receive