How to Print All Terminal Arguments using Bash

Share

In this tutorial, we'll learn how to write a Bash script to print all arguments passed to a script file via terminal in Linux. Although such script isn't very useful for anything in practice, it's a good learning experiment.

Code Snippet

To start, create a new file and call it args.sh, then open it using you preferred source code editor.

Paste the following code in it and save:

#!/usr/bin/env bash
for i in $(seq 0 $#);
do
    echo "\$$i" = ${!i}
done

Understanding the Code

Before executing the script file, let's understand what this code does.

Shebang

The first line is the shebang #!/usr/bin/env bash. This tells what program can be used to execute this script file. In this case, /usr/bin/env bash will execute the bash command wherever it's installed for us.

For... in...; do...done

For for... in...; is the for loop statement in Bash. This will loop through items in a list and execute the code between do and done for each item in the list. Note that in Bash a "list" is just text separated by whitespace.

seq

The seq program outputs a sequence form one number to another. In this case, the first number is 0.

$#

The code $# is where the total number of arguments passed to our script is stored.

In this loop, we'll make the variable i go from 0 to the the total number of arguments.

echo

This command prints to the terminal whatever arguments as pass to it.

\$

This is a escape sequence. In Bash, the dollar sign ($) has a special meaning in syntax, so to use $ literally we need to escape it with a backward slash (\).

$i

This will be replaced by the current value of i in the loop. Combined with the above, "\$$i" will become "$0", "$1", "$2" and so on.

=

This doesn't mean anything. echo will just print it.

${!i}

This is the important part. In Bash, $0 stores the zeroth argument passed to the program, $1 stores the first one, $2 stores the second, and so on.

The syntax ${!...} will output the value of a variable whose name is stored in another variable that you write between ! and }.

When $i is 0, ${!i} will output the value of $0, which is the zeroth argument. When $1 is 1, it will output the value of $1, and so on.

Running the Code

To run this script, open a terminal in the folder where you saved it [how?], then mark it as executable and run it:

chmod +x args.sh
./args.sh first second third fourth

This should output the following:

$0 = ./args.sh
$1 = first
$2 = second
$3 = third
$4 = fourth

Learn More

Comments

Leave a Reply

Leave your thoughts! Required fields are marked *