3

Using kernel 2.6.x

How would you script the result below with the following variables using sh (not bash, zsh, etc.) ?

VAR1="abc def ghi"
VAR2="1 2 3"
CONFIG="$1"

for i in $VAR1; do
   for j in $VAR2; do
      [ "$i" -eq "$j" ] && continue
   done
command $VAR1 $VAR2
done

Desired result:

command abc 1
command def 2
command ghi 3
3

3 Answers 3

7

One way to do it:

#! /bin/sh

VAR1="abc def ghi"
VAR2="1 2 3"

fun()
{
    set $VAR2
    for i in $VAR1; do
        echo command "$i" "$1"
        shift
    done
}

fun

Output:

command abc 1
command def 2
command ghi 3
7
  • You beat me too it by a few seconds, although I did not have it in a function to protect the positional parameters. Neat.
    – Kusalananda
    Sep 4, 2017 at 16:22
  • Does sh support the shift command ?
    – uihdff
    Sep 4, 2017 at 16:25
  • 1
    @uihdff sh supports both functions and shift.
    – Kusalananda
    Sep 4, 2017 at 16:26
  • 1
    @uihdff You can just leave out the enclosing fun() { ... }. But then set $VAR2 overrides script parameters $1, $2, ..., which is probably not what you want. Sep 4, 2017 at 16:27
  • 2
    No. If a third value is to be used than you install a better shell and use arrays. Or you write a wrapper script. Sep 6, 2017 at 6:42
7

A variation on Satō Katsura's answer (here, a self-contained function):

func () {
    var=$1
    set -- $2

    for arg1 in $var; do
        printf 'command %s %s\n' "$arg1" "$1" # or  cmd "$arg1" "$1" directly
        shift
    done
}

func "abc def ghi" "1 2 3"

The following would work, but would overwrite the positional parameters of the script that it is in:

var1="abc def ghi"
var2="1 2 3"

set -- $var2
for arg1 in $var1; do
    printf 'command %s %s\n' "$arg1" "$1"
    shift
done
11
  • Had to add the "CONFIG="$1" variable as I found out this script takes an argument for a file path. How does this change the script ?
    – uihdff
    Sep 4, 2017 at 16:59
  • 1
    @uihdff As long as all references to $1 happens above the non-function solution (like saving $1 in a variable with e.g. CONFIG=$1), it should be ok.
    – Kusalananda
    Sep 4, 2017 at 17:01
  • 1
    @uihdff More importantly, before set -- $var2.
    – Kusalananda
    Sep 4, 2017 at 17:02
  • 1
    @uihdff I wouldn't think so, no. You can always run the script with sh -x ./test.sh /etc/test2.sh to see what actually happens.
    – Kusalananda
    Sep 4, 2017 at 17:07
  • 1
    @uihdff If you put that code in a script, and if that script takes any command line arguments. Then these command line arguments would be replaced by the set call. set -- $var2 would overwrite any existing positional parameters, $1, $2, $3 etc.
    – Kusalananda
    Sep 20, 2017 at 19:33
1

Following is one of the solution.

#!/bin/sh
var1="a b c"
var2="1 2 3"
set -- $var2
for i in $var1
do
    echo $i $1
    shift
done
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .