0

I'm writing a Bash called "NewProject" that creates a second Bash script called "compile". Both scripts must be able to take arguments as input. My problem is that I can not write "$1" into the compile script - this simply copies the contents of NewProject's first argument into the compile script. This is the part of the NewProject script that creates the compile script.

echo "#!/bin/bash" > $1/compile
echo "
if [[ -z '$1' ]];
then
        echo "You are missing file names. Type in: compile -o executable files."
        exit 1
fi" >> $1/compile
chmod u+x $1/compile

And here is output from a test run of the NewProject script.

#!/bin/bash

if [[ -z 'testproject4' ]];

then
        echo You are missing file names. Type in: compile -o executable files.
        exit 1
fi

How can I change the NewProject script so that instead of 'testproject4', the compile script contains '$1'?

1
  • 1
    $ in "" gets interpreted, in '' it doesn't. Also note that you have internal " within your surrounding " (the "You are missing file names..." bit) which might not be what you intended (it doesn't matter in this case because echo echoes all its arguments separated by strings anyway) Commented Feb 5, 2014 at 23:26

2 Answers 2

3

You should be more accurate with quoting.

echo "$1" >>$1/compile

will append the value of NewProject's first argument into the compile script.

However:

echo '$1' >>$1/compile

will append exactly $1 characters into the compile script.

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

2 Comments

BTW: echo "if [[ -z '$1' ]]; then echo "You are missing file names. Type in: compile -o executable files." exit 1 fi" >> $1/compile will not work as you expect. Double quotes cannot be nested, so echo "aa "bb cc dd" ee" >>$1/compile will append aa bb cc dd ee (not aa "bb cc dd" ee) into compile. You should either escape inner "-s (echo "aa \"bb cc dd\" ee" >>$1/compile), or surround "-s with '-s.
To insert $1 into compile, you can either use single quotes (echo '$1' >...) or escape $ with backslash (echo "\$1" >>...).
0

I would use a heredoc

cat <<'END' > "$1"/compile
#!/bin/bash

if [[ -z $1 ]];
then
        echo "You are missing file names. Type in: compile -o executable files."
        exit 1
fi
END
chmod u+x "$1"/compile

When you quote the heredoc terminator word (cat <<'END'), it effectively quotes the entire doc

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.