Bash all arguments print

The purpose of this tutorial is to show how to print all of the arguments submitted from the command line in a Bash script on Linux. There are several different methods for doing this, as you will see in the examples below.

In this tutorial you will learn:

  • How to print all arguments submitted on the command line from a bash script
Bash all arguments print
Bash all arguments print
Software Requirements and Linux Command Line Conventions
Category Requirements, Conventions or Software Version Used
System Any Linux system
Software N/A
Other Privileged access to your Linux system as root or via the sudo command.
Conventions # – requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command
$ – requires given linux commands to be executed as a regular non-privileged user

Bash all arguments print




There are couple ways how to print bash arguments from a script. Try some scripts below to name just few.

  1. In this first script example you just print all arguments:
    #!/bin/bash 
    echo $@
    
  2. If you intend to do something with your arguments within a script you can try somethign simple as the following script:
    #!/bin/bash 
    for i; do 
       echo $i 
    done
    
  3. Next we have some script which are doing the same as the previous bash script but employ different approach:
    #/bin/bash 
    for i in $*; do 
      echo $i 
    done
    
  4. Let’s print all bash arguments using shift:
    #!/bin/bash 
     
    while (( "$#" )); do 
      echo $1 
      shift 
    done
    
  5. Or we can do something obscure like this to print all bash arguments:
    #/bin/bash 
     
    # store arguments in a special array 
    args=("$@") 
    # get number of elements 
    ELEMENTS=${#args[@]} 
     
    # echo each element in array  
    # for loop 
    for (( i=0;i<$ELEMENTS;i++)); do 
        echo ${args[${i}]} 
    done
    

Closing Thoughts

In this tutorial, we saw several different ways to print all of the arguments passed to a Bash script on the command line. As with most things in Linux, there is always more than one way to accomplish a task. Feel free to use whichever method best suits your situation at hand.



Comments and Discussions
Linux Forum