DEV Community


Posted on

Bash arguments

When executing a shell script, you can pass any number of arguments. Let's say, you invoke a bash script like this: ./ "foo bar" baz"
What does the shell script see?


Command line arguments are visible in the shell script from $0 to $9, where $0 is always the path to the shell script the way it was called:

  • ./$0 contains ./
  • path/to/$0 contains path/to/

In other words, this is the path to the script relative to the working directory or an absolute path.

In the example in the introduction of this article, $1 would contain foo bar and $2 baz.

The special variable $@ contains all arguments passed to the script, excluding $0.

Passing arguments to another script

Let's say, we have, which calls and passes all arguments over. In, you pass $@ to But note there's a significant difference if the argument is quoted or not:

If you do ./ "foo bar" baz and that script does ./ $@, it would be substituted to ./ foo bar baz. While we originally only passed 2 arguments to, would receive 3 arguments.

If the first script would instead quote the argument, ./ "$@", it would be substituted to ./ "foo bar" baz.

Looping over arguments

The following example shows how to loop over all arguments passed to a shell script:

#!/usr/bin/env bash

for arg in "$@"
  if [ "$arg" == "--help" ] || [ "$arg" == "-h" ]
    echo "Help argument detected."
Enter fullscreen mode Exit fullscreen mode

Top comments (0)