Home > Blockchain >  How to write a bash script to label each argument like this:
How to write a bash script to label each argument like this:

Time:04-07

$ bash argcnt.sh this is a "real live" test
is
real live

(to display only paired arguments)

Because, I know only in this way:

#!/bin/bash
echo "$2"
echo "$4"

CodePudding user response:

It seems like you want to print every other argument given to the script. You could then create a loop over $@:

#!/bin/bash

# idx will be 2, 4, 6 ... for as long as it's less than the number of arguments given
for ((idx = 2; idx < ${#@}; idx  = 2))
do
    # variable indirection below:
    echo "${!idx}"
done

Note: You can use $# instead of ${#@} to get the number of elements in $@ too. I don't know which one that is preferred by people in general.

CodePudding user response:

If what you want is print every other argument, starting from the second, you can use shift:

$ cat argcnt
#!/bin/bash
while shift; do printf '%s\n' "$1"; shift; done

$ ./argcnt this is a "real live" test foo
is
real live
foo
  • Related