0

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

2 Answers 2

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

first_two="${argv[@]:0:2}"
last_two="${argv[@]:$argc-2:2}"
others="${argv[@]:2:$argc-4}"
Sign up to request clarification or add additional context in comments.

3 Comments

It goes without saying you will probably want to validate [ $argc -ge 4 ] at the beginning. This note is fine, no need to edit, but in answering in the future always try and make sure you point out where validations should occur or grave problem may occur :). You may also point out where an integer value is used, it is good practice to add declare -i (e.g. declare -i argc=$#)
Just another couple of points. When using ${...} syntax, double-quotes are not required. When calculating indexes, the numeric parts are probably better written with $((..)) syntax. (e.g. ${argv[@]:$((argc-2)):2}) You can also use standard index syntax to count-backwards from the last element (e.g. ${argv[@]:(-2)} or without parens leaving a space before the index ${argv[@]: -2})
You don't need argv; you can index $@ directly with ${@:1:2}, ${@: -2:2} (the space is required to avoid interpreting :- as the default expansion operator) and ${@:3:$#-4}.
1
#!/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

3 Comments

Please fix the first line.
Yep, that's the correct one, but in my case i used sed to replace patterns with input.
The parentheses around $#-4 aren't necessary (at the very least, one pair is sufficient).

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.