Badly Placed ()'S Error with the Following Shell Script

Badly Placed ()'S Error with the Following Shell Script

This is the code snippet. Here i am seeing the badly placed ()'s error

#!/bin/sh 
#!/usr/bin/perl -w

# array declaration
arr= (one two three)  # seeing error here

# for loop
for (( i=0;i<4;i++ ))
do
    echo "\n $i : ${a[i]}"
done
1

2 Answers

It is a small error.

arr= (one two three)

should've been

arr=(one two three)

Also you can't use \n in echo. Use printf if you want to use \n.

And fixing the rest of the errors, the code looks like this.

# array declaration
arr=(one two three)  

# for loop
for (( i=0;i<3;i++ ))
do
    printf "\n $((i+1)) : ${arr[i]}"
done
echo ""
arr= (one two three)

Lets break down what this does.

arr=

This part assigns $arr an empty value (temporarily, since it precedes a command).

(one two three)

This part runs one in a subshell with arguments two and three, with the previously assigned value of $arr.

Did you perhaps mean to assign the three values to an array in $arr instead?

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Chloe Bennett
Author

Chloe Bennett

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.