1

I want to build a loop in my shell script where i run over all arguments in reverse order and use them in a command. How can this be done?

My specific code would be:

#!/bin/sh
for MODULE in "$@"
do
rmmod $MODULE
done
for MODULE in "$@"
do
insmod $MODULE
done
dmesg -c

but i want the "insmod" in the second for-loop to be called with the arguments from last to first instead.

5
  • 1
    Do you need to use #!/bin/sh, or are you assuming that you'll be using bash? Commented Apr 30, 2020 at 16:12
  • The simplest solution is to build an array in reverse order while traversing "$@", or to use a C-style for loop, but /bin/sh doesn't necessarily support either. Commented Apr 30, 2020 at 16:13
  • How can i check what i have available? If I do echo $SHELL on the device i want to run this, i get /bin/sh as answer Commented Apr 30, 2020 at 16:51
  • If /bin/bash exists you can (and should) use it in scripts by changing the shebang line to #!/bin/bash. Then you get access to many more features. Commented Apr 30, 2020 at 17:07
  • /bin/bash does not exist, thanks for clarifying Commented Apr 30, 2020 at 18:42

1 Answer 1

3

If you're targeting plain sh and not bash then you won't have any array features to speak of. You could use a recursive function:

#!/bin/sh

resetmods() {
    rmmod "$1"
    [ "$#" -gt 1 ] && (shift; resetmods "$@")
    insmod "$1"
}

resetmods "$@"
dmesg -c
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.