How to write a bash script to label each argument like this:
$ bash argcnt.sh this is a "real live" test
there are 5 arguments
arg1: this
arg2: is
arg3: a
arg4: real live
arg5: test
Cause whatever I do it's only counting as 6 arguments
CodePudding user response:
For one, you are trying to do different formats, resulting in it being an incorrect size.
this is a "real live" test
This won't work because you used quotes on a few words, counting that argument as just one argument.
this is a real live test
Would work, counting each word as a different argument.
For 2, you are making the code more complicated than it has to be. You are echoing each command individually, instead of making a for loop that does the heavy lifting.
echo "There are $# arguments"
$# tells you the number of arguments there are.
i=1
for arg in $@;
do
echo -e "arg$i: $arg\n"
i =1
done
This creates a loop that prints out every argument given and how many arguments there are
CodePudding user response:
You're on the right track. In your example, "real live"
is treated as one input. It's in variable $4
.
#!/bin/bash
echo "there are $# arguments"
echo "arg1: $1"
echo "arg2: $2"
echo "arg3: $3"
echo "arg4: $4"
echo "arg5: $5"
When you run this with your input, it should give you the output that you stated.