How to use command line arguments in a shell script

19,489

You can access the command line arguments in your shell script with the special variables $1, $2 until $9. $0 is the name of your script.

If you need access more than 9 command line arguments, you can use the shift command. Example: shift 2 renames $3 to $1, $4 to $2 etc.

Please remember to put the arguments inside doubles quotes (e.g. "$1"), otherwise you can get problems if they contain whitespaces.

Share:
19,489

Related videos on Youtube

Phil_Charly
Author by

Phil_Charly

Kallithea city rocks. Listening Xatzifrageta now, plz not disturb.

Updated on September 18, 2022

Comments

  • Phil_Charly
    Phil_Charly almost 2 years

    I have a shell script and when invoking it ./test it asks for an input.I 've seen a quicker way just by writing at once ./test myInput ,how is that achievable?

  • Angel Todorov
    Angel Todorov over 10 years
    You can use "double-digit" parameters directly, just use braces: echo ${12}
  • DoxyLover
    DoxyLover over 10 years
    Also, $# gives you the number of arguments. For example, with ./test.sh a b c, $# would evaluate to 3.
  • crs1138
    crs1138 over 6 years
    @glennjackman – should I be using the quotes around the parameter as in echo "${12}" or is the syntax sufficient as echo ${12}. What is the difference?
  • Angel Todorov
    Angel Todorov over 6 years
    Using double quotes will prevent the shell from performing word splitting and filename expansion. Use of braces allows you to use double-digit positional parameters, and to disambiguate variable names from surrounding text.
  • Angel Todorov
    Angel Todorov over 6 years
    Demo: set -- one two three four five six seven eight nine ten eleven "12 twelve"; printf "%s\n" "${12}"; printf "%s\n" ${12}