0

Let's consider the following code

#!/bin/bash

var=$(
        cat <<-EOF
                Foo Bar
        EOF
)

echo "${var}"

This works as expected with tabs, i.e the var variable holds assigned Foo Bar

However, consider a situation where I cat out this file on terminal, and copy paste the content of this script to another file instead of using cp or scp

Now, the script would contain spaces instead of tabs, so the same script above would give errors with spaces instead of tabs

So, I would like to modify the script with unexpand before coninuing to execute the program always

I tried modifying the code above like so

#!/bin/bash

unexpand --first-only $0 | sponge $0

var=$(
        cat <<-EOF
                Foo Bar
        EOF
)

echo "${var}"

This works the second time around, and I know why that's happening

But I want to make this program run correctly the first time around, how do I modify my script so that it runs correctly the first time around with spaces instead of tabs

Note: I know this could be done by splitting the file into 2 separate scripts, but I do not want do that. I would like to have only one single script.

1 Answer 1

0

Trying to modify the source of the script that's running seems like a path to nasal demons.

How about something like (untested):

#!/usr/bin/env bash

: ${TMPDIR='/usr/tmp'}
tmpfile=$(mktemp)
tooldir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
if [[ "$tooldir" != "$TMPDIR" ]]; then
    # copying first to get the same permissions on the tmp as on the original
    cp "$0" "$tmpfile" &&
    unexpand --first-only "$0" > "$tmpfile" &&
    "$tmpfile" "$@"
fi

var=$(
        cat <<-EOF
                Foo Bar
        EOF
)

echo "${var}"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .