0

Following is the code for extracting input from command line into bash script:

input=(*);
for i in {1..5..1}
do
    input[i]=$($i);
done;

My question is: how to get $1, $2, $3, $4 values from input command line, where command line code input is:

bash script.sh "abc.txt" "|" "20" "yyyy-MM-dd"

Note: Not using for i in "${@}"

2
  • What is wrong with for i in "$@"; do...? Do you just not like it? Commented Feb 29, 2016 at 8:17
  • You can simply write for i; do..., without adding in "$@". I think this is the most natural way to traverse over the input parameters. Commented Feb 29, 2016 at 11:14

3 Answers 3

2
#!/bin/bash

for ((i=$#-1;i>=0;i--)); do 
  echo "${BASH_ARGV[$i]}"
done

Example: ./script.sh a "foo bar" c

Output:

a
foo bar
c
Sign up to request clarification or add additional context in comments.

1 Comment

In bash script we can extract input value using '$1', '$2' etc... so how can we extract that values using for loop, where 1, 2 values are coming pragmatically.
0

I don't know what you have against for i in "$@"; do..., but you can certainly do it with shift, for example:

while [ -n "$1" ]; do
    printf " '%s'\n" "$1"
    shift
done

Output

$ bash script.sh "abc.txt" "|" "20" "yyyy-MM-dd"
 'abc.txt'
 '|'
 '20'
 'yyyy-MM-dd'

Personally, I don't see why you exclude for i in "$@"; do ... it is a valid way to iterate though the args that will preserve quoted whitespace. You can also use the array and C-style for loop as indicated in the other answers.

note: if you are going to use your input array, you should use input=("$@") instead of input=($*). Using the latter will not preserve quoted whitespace in your positional parameters. e.g.

input=("$@")
for ((i = 0; i < ${#input[@]}; i++)); do
    printf " '%s'\n" "${input[i]}"
done

works fine, but if you use input=($*) with arguments line "a b", it will treat those as two separate arguments.

Comments

0

If I'm correctly understanding what you're trying to do, you can write:

input=("$@")

to copy the positional parameters into an array named input.

If you specifically want only the first five positional parameters, you can write:

input=("${@:1:5}")

Edited to add: Or are you asking, given a variable i that contains the integer 2, how you can get $2? If that's your question, then — you can use indirect expansion, where Bash retrieves the value of a variable, then uses that value as the name of the variable to substitute. Indirect expansion uses the ! character:

i=2
input[i]="${!i}"     # same as input[2]="$2"

This is almost always a bad idea, though. You should rethink what you're doing.

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.