DEV Community

Tenry
Tenry

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: ./script.sh "foo bar" baz"
What does the shell script see?

Variables

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:

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

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 script1.sh, which calls script2.sh and passes all arguments over. In script1.sh, you pass $@ to script2.sh. But note there's a significant difference if the argument is quoted or not:

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

If the first script would instead quote the argument, ./script2.sh "$@", it would be substituted to ./script2.sh "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 "$@"
do
  if [ "$arg" == "--help" ] || [ "$arg" == "-h" ]
  then
    echo "Help argument detected."
  fi
done
Enter fullscreen mode Exit fullscreen mode

Discussion (0)