Search code examples
pythonbashbash-function

How to get and compare Bash Function parameters?


this should be a simple answer but I haven't been able to find a simple solution. I'm trying to create a bash script that runs the reindent.py tool scrip but I want to be able to get user input on whether or not he wants to write the file back to disk. Basically I want to type reindent_python -n FILE_PATH or reindent_python FILE_PATH. So far I got the following:

function reindent_python () {
    if ["$1" = "n"]; then
        ./reindent.py -n $2
    else
        ./reindent.py $2
    fi
}

Since this is my first shell script I'm not sure how to get whether or not the first parameter is -n and is $1 the n parameter and $2 the FILE_PATH? How would I got about creating this script?

Thank you!


Solution

  • First off, what you display is a function, not a script. Your function could be as simple as:

    function reindent_python () {
        ./reindent.py "$@"
    }
    

    given the fact that your Python script appear to take the same arguments as your function. You can simply pass them all to the Python script with the above construct.

    As @CharlesDuffy mentions in the comment, the function keyword is not necessary:

    reindent_python () {
        ./reindent.py "$@"
    }
    

    That aside, the if part should be

    [ "$1" = "-n" ];
    

    with a space around the brackets and a dash before the n.