2
su "$uname" -c "cat > ~/scripts/syncdownloads.sh <<ENDMASTER
"#!/bin/bash"
login="$flogin"
pass="$fpass"
host="$fhost"
remote_dir="$fremote_dir"
local_dir="$flocal_dir" 

base_name="$(basename "$0")"
lock_file="/tmp/$base_name.lock"
trap "rm -f $lock_file exit 0" SIGINT SIGTERM
if [ -e "$lock_file" ]
then
    echo "$base_name is running already."
    exit
else
    touch "$lock_file"
    lftp -p 22 -u "$login","$pass" sftp://"$host" << EOF
    set sftp:auto-confirm yes
    set mirror:use-pget-n 5
    mirror -c -P5 "$remote_dir" "$local_dir"
    quit
EOF
    rm -f "$lock_file"
    trap - SIGINT SIGTERM
exit
fi

ENDMASTER"

The above is my part of my code, basically I want a way to insert the values at the top of the file that the user has entered (from login to local_dir) but then leave the rest of the lines till the ENDMASTER statement exactly as they appear now.

I've tried commenting every line individually and together with single and double quotes but when I run the bash script it always completes the commands from base_name onwards regardless and when I open the file generated the rest is blank after trap.

I am new to bash so any help would be greatly appreciated as I cannot find anything relevant on-line.

4

How about turning parameter substitution in the here-document off? (See Example 19-7 on www.tldp.org for more details.)

Maybe your script will look better like this (although it is still pretty dense):

su "$uname" -c "cat > ~/scripts/syncdownloads.sh << 'ENDMASTER'
###### Using `$()` to create a sub shell so that we don't have to escape 
###### special characters.
$(
###### The parameter substitution is on here
cat <<INNERMASTER
#!/bin/bash
login="$flogin"
pass="$fpass"
host="$fhost"
remote_dir="$fremote_dir"
local_dir="$flocal_dir"

INNERMASTER

###### No parameter substitution
cat <<'INNERMASTER'
base_name="$(basename "$0")"
lock_file="/tmp/$base_name.lock"
trap "rm -f $lock_file exit 0" SIGINT SIGTERM
if [ -e "$lock_file" ]
then
    echo "$base_name is running already."
    exit
else
    touch "$lock_file"
    lftp -p 22 -u "$login","$pass" sftp://"$host" << EOF
    set sftp:auto-confirm yes
    set mirror:use-pget-n 5
    mirror -c -P5 "$remote_dir" "$local_dir"
    quit
    EOF
    rm -f "$lock_file"
    trap - SIGINT SIGTERM
    exit
fi

INNERMASTER
)
ENDMASTER"

This way you don't have to escape anything.

2

Preceed the dollar signs with a backslash:

lock_file="/tmp/\$base_name.lock"

and so on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.