Question

I was using a quick and dirty BASH script to automate a CF partitioning process.
This worked well until I wanted to add to it.

Basically, I have a script which partitions a compact flash as such:

CMD=.fdisk
DEV=/dev/sdc

echo "Calculating partition sizes..."
P1SIZE=+1100M
P2SIZE=+1200M

echo "Creating instruction file..."
PT1="n p 1\n $P1SIZE"
PT2="n p 2\n $P2SIZE"
END="a 1 w EOF\n"

[ -e $CMD ] && rm -rf $CMD

for i in $PT1 $PT2 $END; do echo -e $i >> $CMD; done

echo "Creating partitions..."
fdisk $DEV << EOF < $CMD
[ -e $CMD ] && rm -f $CMD

The idea is that in the future the file represented by '$CMD' will be created automatically by an external tool with the proper start and end values. Right now I simply accept the default start and provide a size.

This worked quite well until I wanted to incorporate a few additional steps to my script. But I got into problems when I noticed weird behaviors.

The first is that if I add the code above inside a function, I will keep getting a script error:

line XX: syntax error: unexpected end of file

Also, I realized that any additional code after the 'fdisk' command will not execute and the script seems to simply terminate (without errors, $? = 0).

Does anyone know why the function doesn't work and the script terminates?

Was it helpful?

Solution

You've started a heredoc (<< EOF), but you never end it anywhere.

OTHER TIPS

A rule of thumb is that the 'limit string' you use (I was using 'EOF' in my case, but you can use anything you want) must not have spaces (or tabs) in front of it. If it does, it will not be considered the end.

Example:

myFunction() {
    cat << EOF
        Hello
        World
        EOF
}

The 'EOF' above is considered regular text because it has spaces in front of it! If you write the following instead:

myFunction() {
    cat << EOF
        Hello
        World
EOF
}

It will now work!

If you insist on using spaces, then you can suppress the tabs by using a '-' character to the immediate right of the '<<' characters.

Example:

myFunction() {
    cat <<- EOF
        Hello
        World
        EOF
}

Note that this only works for tabs and not spaces! This is great to keep your code a bit more readable.

Also note that if you quote the 'limit string', you end up disabling parameter substitution. So if you want to write text that should not be substituted or executed, this makes it possible:

cat << "EOF"
    Type `ls -la` at the command prompt
EOF
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top