1

I have a script in bash which basically creates a user and install all the necessary applications.

It works the way that it iterates through a couple of commands, where I put a variable at the end of the command (positional argument).

I've set it up this way

function Install
{
    COMMANDS=(
        "Do_1st_thing $1"
        "Do_2nd_thing $1"
        "Do_3rd_thing $1"
    )
    
    for CMD in "${COMMANDS[@]}" ; do
        $CMD
    done
}

Then I run it

Install first_argument

The problem is that the first command is successful, however every next command says "Command not found".

Does the first positional argument ($1) changes after the execution of the first command? Would I have to "eval" the "$CMD" in the "for loop" to get it working?

Feel free to ask any question, I will do my best to answer them.

Thank you for your help, Kris

2 Answers2

1

You are declaring an array with the first argument hard-coded in. If $1 is "foo" you are declaring

    COMMANDS=(
        "Do_1st_thing foo"
        "Do_2nd_thing foo"
        "Do_3rd_thing foo"
    )

Storing these commands in an array seems like a weird thing to do anyway. Just

Install () {
    Do_1st_thing "$@"
    Do_2nd_thing "$@"
    Do_3rd_thing "$@"
}

If your commands don't all accept the same arguments, you need to refactor the code, but that seems to be outside the scope of your concrete question here.

If they do, you might also consider refactoring into

    commands=(Do_1st_thing Do_2nd_thing Do_3rd_thing)
    for cmd in "${commands[@]}"; do
        "$cmd" "$@"
    done

(Notice also Correct Bash and shell script variable capitalization)

Maybe see also http://mywiki.wooledge.org/BashFAQ/050

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Thank you @tripleee. I've put those commands into the array as I want to iterate through them and if I meet certain command I can ask "myself" if I want to execute that command or not (I didn't include the code here). They all need to accept the same argument. – Krzysztof Cyran Oct 27 '20 at 10:11
  • Hmm I think it was a bit overcomplicated. If I don't put those commands into a list, but rather run them like this `Install () { Do_1st_thing "$@" Do_2nd_thing "$@" Do_3rd_thing "$@" }` do the job. Thanks a lot for your help – Krzysztof Cyran Oct 28 '20 at 14:04
-1

As this is a bash function, you don't need the word function to designate it as a function. You would therefore write the code as below:

#!/bin/bash
Install()
{
  COMMANDS=(
    "ls $1"
    "stat $1"
    "file $1"
   )

  for CMD in "${COMMANDS[@]}" ; do
     $CMD
  done
}

Install testfile.txt
Raman Sailopal
  • 12,320
  • 2
  • 11
  • 18
  • While I agree that the `function` keyword is unnecessary and usually should be left out, this does nothing to actually solve the OP's problem. – tripleee Oct 27 '20 at 09:28