0

I need to generate the following file content with the bash script.

#!/bin/sh
script_dir=$(dirname "$(realpath $0)")
export LD_LIBRARY_PATH=$script_dir/lib
exec $script_dir/{EXEC_FILE_WITH_EXT}

i.e. something like

my_script_generator.sh

#!/bin/sh
echo "<filecontent above>" > new_script.sh

The problem's a make all screening correctly to avoid echo evaluate the content and put it just as is. For the more huge script, it becomes a problem.

Is there an online service that simplifies that work?

nen777w
  • 87
  • 1
  • 1
  • 6
  • You are using `bash` or POSIX `sh`? – Inian Jun 23 '21 at 08:43
  • 1
    Also `{EXEC_FILE_WITH_EXT}` will be converted as a literal string i.e. why isn't there a preceding `$` if its a variable? – Inian Jun 23 '21 at 08:45
  • 1
    `problem's a make all screening correctly to avoid echo evaluate the content and put it just as is` What is "screening"? `Is there an **online** service` How did you go from "evaluating echo" to an "online service"? Why do you need an online service? What you want is a __templating__ system - there are many templating engines available. Basically, you want to just to _substitute_ the `{EXEC...}` part with some other thing _in your template_? – KamilCuk Jun 23 '21 at 08:46
  • If OP wants to expand `EXEC_FILE_WITH_EXT` to a real executable name, then I do not agree with the duplicate. Duplicate is about multiline strings - without expansions in inside the string, without templating part. @nen777w please clarify your question. – KamilCuk Jun 23 '21 at 08:52
  • 1
    @KamilCuk: Agreed, feel free to remove the dupe in that case, but I think its just a typo on their side, missing out `$` – Inian Jun 23 '21 at 08:54
  • You can use the accepted answer with `<<'EOM'` instead of `< – Inian Jun 23 '21 at 08:58

1 Answers1

1

Use cat+here-document and backslash before $ signs you dont't want to be evaluated.

#!/bin/sh

cat > new_script.sh <<EOF
#!/bin/sh
script_dir=\$(dirname "\$(realpath \$0)")
export LD_LIBRARY_PATH=\$script_dir/lib
exec \$script_dir/{EXEC_FILE_WITH_EXT}
EOF

A script like this (not bullet proof) could help automate the task

#!/bin/sh

# make-script.sh
# input : a sequence of commands
# output : sequence of commands which generates a copy of the source script file
echo "cat <<EOF"
echo "#!/bin/sh"
echo

sed "s/\\\$/\\\\\\\$/g" 
echo "EOF"

Michel Billaud
  • 1,758
  • 11
  • 14