2

Here is the code

#file is named getpack2
count=0
while [ -n "$*" ] ; do
    ARRAY[${count}]=$1
    shift
    count=`expr $count + 1`
done

for t in "${ARRAY[@]}"; do
    mkdir $t
    cd $t
    touch hello
    cd ..
done

the line im using to run this is:

getpack2 vocals-doo flute-wood

this creates the desired directories and files

this will also work:

./getpack2 vocals-doo flute-wood

however, when I prefix the command with sudo:

sudo ./getpack2 vocals-doo flute-wood

it gives me the following errors

./getpack2: 7: ARRAY[0]=vocals-doo: not found
./getpack2: 7: ARRAY[1]=flute-wood: not found
./getpack2: 15: Bad Substitution

I'm very new to shell scripting. Just started learning it today. Is there some sort of scoping error?

2
  • Why are you computing the argument count? It is available in $# Commented Mar 4, 2012 at 0:48
  • Rather than doing "cd ..", you can cd in a subshell: mkdir $t; (cd $t; touch hello; ). The cd and touch happen in a different shell, and the original shell stays in the same directory. This is much less error prone (as the script grows in complexity, it becomes harder to keep track of the original directory and ensuring a cd back can become challenging.) Commented Mar 4, 2012 at 0:50

1 Answer 1

5

Your superuser (root) may have a different shell that does not support arrays (for instance dash or some other small shell.) Try to program using only standard bourne shell constructs. Or include in the header of your script the interpreter to use:

#! /bin/bash
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.