Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get the next element in $@

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
  1. Always quote "$@" — that’s the only way to keep "arguments with whitespace" together.
  2. in bash, use [[...]] instead of [...] — the double bracket form is more safe regarding unquoted variables.
  3. 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; then
    

    Carefully read help if at a bash prompt.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading