2

I have a python script (called temp.py) that returns two numbers, formatted as strings and separated by whitespace. For example, the output would look like "23.3 43.6 ". I am trying to print out these values in a bash script. I can print the entire output string via echo $OUTPUT, but I get a bad substitution error when trying to print individual elements. What am I doing wrong?

#!/bin/bash OUTPUT=$(python ./scripts/temp.py) echo $OUTPUT # Prints normally "23.3 43.6 " echo ${OUTPUT[0]} # error: bad substitution! 
3
  • 2
    Sounds like you are not using bash. Are you maybe calling the script with sh instead?
    – terdon
    CommentedMar 4, 2021 at 18:12
  • @terdon: this is bash script.CommentedMay 12, 2021 at 8:16
  • @JoonhoPark um. Yes, I know it is a bash script. However, the error the OP describes suggests that this bash script is not being run as a bash script but instead it is being run as an sh script. See my answer.
    – terdon
    CommentedMay 12, 2021 at 8:18

1 Answer 1

3

You have two problems there. First, you are using a shell that doesn't support arrays. Most likely sh or dash. My guess is that although you have a bash shebang line there, you are calling your script with sh script.sh which means it is being interpreted by whatever sh is on your system. For example, on dash (which is the default sh on Debian and Ubuntu), you get:

$ out=$(echo 23.3 43.6 ) $ echo ${out[0]} dash: 2: Bad substitution 

However, in bash, you would get:

$ out=$(echo 23.3 43.6 ) $ echo ${out[0]} 23.3 43.6 

The next issue is that even if you run this in bash, that isn't how arrays work:

$ out=$(echo 23.3 43.6 ) $ echo ${out[0]} 23.3 43.6 $ echo ${out[1]} ## prints nothing but a newline since the variable is empty $ 

To get an array in bash, you need to put the elements inside parentheses:

$ out=( $(echo 23.3 43.6 ) ) $ echo ${out[0]} 23.3 $ echo ${out[1]} 43.6 
3
  • It will be run by bash when called by filename directly such as "$script.sh".CommentedMay 12, 2021 at 8:20
  • @JoonhoPark yes, of course it will. But, if it were called by bash it would not give the error described by the OP. To get what the OP describes, you need to run this with another shell. And what usually happens is that people run it with sh script.sh thinking that sh is the same as bash. Please read the question more closely and you will see the error described.
    – terdon
    CommentedMay 12, 2021 at 8:27
  • your answer is correct and useful to me.CommentedMay 12, 2021 at 8:41

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.