I’m trying to parse args like I do in C:
if (str[i] == something && str[i + 1] == something) {
//do somthing
}
I can’t figure out how to do the str[i + 1]. Here’s what I tried:
for a in $@ ; do
if [ $a == "create" ] && [sed 's/table/']; then
echo "create database"
fi
done
I’m trying to to something if I find create and right after create if there’s database.
>Solution :
In bash, we can use indirect variables to do the same thing:
for ((i = 1, j = 2; i < $#; i++, j++)); do
if [[ ${!i} == "create" && ${!j} == "database" ]]; then
echo "create database
break
fi
done
This technique does not consume the arguments like shift does.
Ref: 4th paragraph of 3.5.3 Shell Parameter Expansion
A couple of points about your code:
for a in $@ ; do
if [ $a == "create" ] && [sed 's/table/']; then
echo "create database"
fi
done
- Always quote
"$@"— that’s the only way to keep"arguments with whitespace"together. - in bash, use
[[...]]instead of[...]— the double bracket form is more safe regarding unquoted variables. - the brackets are not mere syntax,
[is a command. For external commands, don’t use brackets:if [[ $a == "create" ]] && sed 's/table/other/' some_file; thenCarefully read
help ifat a bash prompt.