Get Python 3 from bash file using similar syntax for Python 3
<p>I am writing an install script and is trying to get a variable linking to Python 3 instead of Python 2. In bash you can do:</p>

<pre><code>:~$ export PYTHON="${PYTHON:-python}"
:~$ echo $PYTHON
/usr/bin/python2
</code></pre>

<p>How would you call similar syntax for Python 3 instead? I have tried</p>

<pre><code>:~$ export PYTHON="${PYTHON:-python3}"
</code></pre>

<p>but it doesn't work.</p>

<p>Your original, Python 2 code doesn't do what you think it's doing:</p>

<pre><code>:~$ export PYTHON="${PYTHON:-python}"
:~$ echo $PYTHON
/usr/bin/python2
</code></pre>

<p>This is because <code>${foo:-bar}</code> expands the variable named <code>foo</code>, or -- if that variable is either unset or set to an empty value -- expands instead to the value <code>bar</code> as a default. If the result is not <code>bar</code>, then that means that <code>$foo</code> must already be set to a non-<code>bar</code> value.</p>

<p>The logic of this command is roughly thus:</p>

<ul>
<li>If no shell variable named <code>PYTHON</code> exists, or such a variable exists but with an empty value, then export an environment variable -- and also set a shell variable -- named <code>PYTHON</code>, with a value being <code>python</code>. (Not <code>/usr/bin/python2</code>, but exactly <code>python</code>, those six precise characters).</li>
<li>If a shell variable named <code>PYTHON</code> does exist with a nonempty value, then export it with its current value to the environment. (If that variable is already exported, then this line has no effect).</li>
</ul>

<p>Since <code>echo $PYTHON</code> is emitting as output <code>/usr/bin/python2</code>, then this means that <code>PYTHON=/usr/bin/python2</code> must have been true <strong>before</strong> your original command was invoked at all.</p>

<hr>

<p>If, unlike your original command, you want to disregard the original value of the <code>PYTHON</code> shell variable (or environment variable, if it's already been <code>export</code>ed), then you should do something like the following:</p>

<pre><code>PYTHON=$(type -P python3) || {
  echo "python3 not found" &gt;&amp;2
  exit 1
}
export PYTHON
</code></pre>

<p>The <code>export</code> is done as a separate command here so that the exit status of <code>export</code> does not override the exit status of <code>type</code>, which would prevent errors from being detected.</p>

python bash python-3.x