0

I am currently trying to rename an input argument by the variable "i" in the following for loop:

cd $1
num=$(echo $#)
echo $num
echo $@
echo "This is the next part where I print stuff"
for i in $(seq 2 $num)
        do
        echo $i
        echo ${!i}
        Args_array+=$(printf '${arg_%s[@]}' ${i})
        echo $Args_array
        arg_${i}=$(ls ${!i})
done

The output is as follows:

4
output_folder /path/to/my.tsv /path/to/my2.tsv /path/to/my3.tsv
2
/path/to/my.tsv
${arg_2[@]}
/var/spool/slurm/d/job6985121/slurm_script: line 23: arg_2=/path/to/my.tsv: No such file or directory

But it will not allow me to rename the $2, $3 arguments with "i" like this. Any help would be appreciated.

I want to pass these arguments into R and have to put them in arg_1, arg_2, etc. format.

3
  • Dynamic variable names are messy; why not just use a proper array? Commented Aug 1, 2022 at 23:29
  • @GordonDavisson I need to be able to use this function for a wide range of data inputs. My idea is that I would use the dynamic variables so that I wouldn't have to manually change my script when the number of arguments changes (which would be every time I would run the R script these arguments are being passed into. If there is a way to do that, your advice would be greatly appreciated. I am very new to coding and I am not even sure what to google at this point. Thank you again. Commented Aug 2, 2022 at 3:14
  • 1
    What is num=$(echo $#)?? Wouldn't num=$# make more sense? Commented Aug 2, 2022 at 7:38

1 Answer 1

1

Not sure I understand what's being attempted with Args_array so focusing solely on OP's comment: 'have to put them in arg_1, arg_2' and skipping arg_1 since OP's code doesn't appear to care about storing $1 anywhere; then again, is R not capable of processing input parameters from the command line?

One bash idea:

$ cat testme
#!/usr/bin/bash

num=$#

for ((i=2;i<=$num;i++))
do
    declare args_$i=${!i}
done

for ((i=2;i<=$num;i++))
do
    typeset -p args_$i
done

Taking for a test drive:

$ testme output_folder /path/to/my.tsv /path/to/my2.tsv /path/to/my3.tsv
declare -- args_2="/path/to/my.tsv"
declare -- args_3="/path/to/my2.tsv"
declare -- args_4="/path/to/my3.tsv"
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! Using "declare" worked. The array I am using is because I would like to pass in arguments to an R script as folllows: /Script.R ${arg_2[@]} ${arg_3[@]} ${arg_4[@]}

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.