0

I want to make a script that make a script that create a file in the folder stocked

Here I'm stocking the folder path of Banana in stock then I want to create a file in that folder

echo "stock=banana/" >> test.sh
echo "touch $stock/file" >> test.sh

When I open test.sh :

stock=banana/
touch /file

why isn't $stock there?

1
  • BTW, note that touch $stock/file isn't safe in general -- that'll fail badly if the content of that variable contains whitespace, and particularly if it breaks into words that can be expanded as a glob character. Always quote your expansions: touch "$stock"/file or touch "$stock/file". Commented Nov 27, 2017 at 15:38

1 Answer 1

1

Doing It Right

If the content you want to insert is hardcoded, use a quoted heredoc:

# Because of the quotes around EOF, nothing inside this heredoc is modified.
cat >test.sh <<'EOF'
stock=banana/
touch "$stock/file"
EOF

If it's not hardcoded, then an unquoted heredoc becomes appropriate -- but requires some care:

#!/bin/bash
#      ^^^^-- /bin/sh does not support any means of eval-safe quoting
#             ...a ksh derivative such as bash will provide printf %q

stock=banana/                    # Presumably this is coming from a generic source, ie. $1
printf -v stock_q '%q' "$stock"  # Generate an eval-safe quoted version of stock

# Because the sigil is not quoted, expansions inside the heredoc are performed unless
# they're escaped.
cat >test.sh <<EOF
stock=$stock_q
touch "\$stock/file"
EOF

Note that we're using printf %q to generate a safely-escaped version of the value and inserting that (in an unquoted context) into the generated script; and being sure to escape all expansions which are intended to be performed by the child shell (thus replacing $stock with \$stock).

Answering The "Why"

Your "$stock" was expanded by the original shell, before it was passed to echo.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.