sorry I am new to the bash scripting since I was used to c shell programming. I am writting a script in bash for which I have to create an array in bash. I was able to do parse one variable through command line by doing": Lets say the below code is part of temp.bash and is called like:
temp.bash -n x -m z
while [ $1 ]; do
if [ $1 == "-n" ]; then
shift
n=$i
else [ $1 == "-m" ]
shift
name=$1
shift
fi
done
echo $n
echo $name
O/P
x
z
I want a code such that is I pass temp.bash -n x y z -m l k z, the ouput should be
x y z
l k z
That is in an array. Currently I can only pass one character. Can anybody help?
Thanks in advance
A string with spaces in it is not the same thing as an array.
I don't think your if-statement if [ $1 ] does precisely what you think it does.
I'd take a slightly different approach:
WHERE=""
# $# is the number of arguments.
# While the number of arguments is greater than 0, keep looping.
while [ "$#" -gt 0 ]
do
case "$1" in
-n) WHERE="n" ;;
-m) WHERE="name" ;;
*) # All other arguments
case "$WHERE" in
n) n="$n $1" ;;
name) name="$name $1" ;;
*) ;;
esac
;;
esac
shift
done
Thanks Corona688. I used the code but I am getting syntax error near unexpected token `"$WHERE"`
case "$WHERE" in
It might be verbose but I thought I will write it again what I used"
WHERE=""
while ["$#" -gt 0 ]
do
case "$1" in
-n) WHERE="n" ;;
-m) WHERE="name" ;;
case "$WHERE" in
n) n="$n $1"
name) name="$name $1"
esac
;;
esac
shift
done
echo $n
echo $name
when I type temp.bash with this code like: temp.bash -n x y -m l k, I am expecting to get result:
x y
l k
instead I get the error message describe above.