0

I am new to bash scripts and i tried a bash script, i want to echo the VER when there is an argument called -v after the first argument (-v should not be there at the first argument's position). I tried following script and it didnot work. It would be great if someone guides. Thanks in advance.

#!/bin/bash
VER=1.0
for var in ${@:-1}
do
  if [ "$var" = v ]; then
    echo $VER
  fi
done
jenny
  • 500
  • 7
  • 22
  • 1
    You need spaces around the `=` in the `if [ $var=="-v" ]; then` line. `bash` parses commands into multiple tokens by splitting around the characters defined by a variable called IFS (Internal Field Separator) which by default contains space, tab and newline, and the `=` operator needs to be parsed as a separate token – Aaron Jul 31 '19 at 16:11
  • 3
    Remember to check your script with http://shellcheck.net – KamilCuk Jul 31 '19 at 16:15
  • `-v should not be there at the first argument's position` this behavior can be disturbing for users as it is not normal. You could use [getopts](https://stackoverflow.com/questions/16483119/an-example-of-how-to-use-getopts-in-bash), it will help you to create a standard script with arguments. – Corentin Limier Jul 31 '19 at 16:25
  • Moreover, exactly the wrong thing is quoted; it should be `[ "$var" = -v ]` -- there's no reason to quote `-v`, but failing to quote `"$var"` makes behavior quite dependent on the variable's contents and other internal state. – Charles Duffy Jul 31 '19 at 17:15
  • @CharlesDuffy Yes okay :) – jenny Aug 01 '19 at 03:34
  • I found the solution, i have to use `for var in "${@#*$1}"` to iterate after the first argument. – jenny Aug 01 '19 at 07:27

0 Answers0