Sergey Tekotin
Sergey Tekotin

Reputation: 71

Passing script to array

I have a bash script which runs as follows:

./script.sh var1 var2 var3.... varN varN+1

What i need to do is take first 2 variables, last 2 variables and insert them into file. The variables between 2 last and 2 first should be passed as a whole string to another file. How can this be done in bash?

Of course i can define a special variable with "read var" directive and then input this whole string from keyboard but my objective is to pass them from the script input

Upvotes: 0

Views: 1691

Answers (2)

Andrey Skuratovsky
Andrey Skuratovsky

Reputation: 687

#!/bin/bash

# first two
echo "${@:1:2}"
# last two
echo "${@:(-2):2}"
# middle
echo "${@:3:(($# - 4))}"

so sample

./script aaa bbb ccc ddd eee fff gggg hhhh
aaa bbb
gggg hhhh
ccc ddd eee fff

Upvotes: 1

Dev Woman
Dev Woman

Reputation: 88

argc=$#
argv=("$@")

first_two="${argv[@]:0:2}"
last_two="${argv[@]:$argc-2:2}"
others="${argv[@]:2:$argc-4}"

Upvotes: 5

Related Questions