Consider the following bash scripts:
#!/bin/bash
cat << EOF > file
$@
VAR=`cat somefile`
EOF
I want to write a file called file
such that $@
is evaluated but cat something
is not. In other words I want the output to look like this:
Arg1 Arg2 Arg3 Arg4
VAR=`cat something`
If I use 'EOF'
instead of EOF
, then nothing gets evaluated, but I want $@
to be evaluated.
CodePudding user response:
Have you tried escaping the characters? Using "\`":
cat <<EOF > file
$@
VAR=\`cat testfile\`
echo \$VAR
> EOF
Here is the file content:
cat file
VAR=`cat testfile`
echo $VAR
Then execute it:
./file
Hi!
CodePudding user response:
If the variable to be expanded is at the beginning or at the end of the heredoc then you could use a quoted heredoc grouped with other printing instructions. also, expanding variables in foreign code is dangerous if you don't implement the proper escaping.
#!/bin/bash
{
# here I suppose that "$@" contains a command and it's arguments
printf '%q ' "$@"
echo
cat <<'EOF'
VAR=$( < testfile )
echo "$VAR"
EOF
} > file.sh