How can I pass a command line argument into a shell script?

  • I know that shell scripts just run commands as if they were executed in at the command prompt. I'd like to be able to run shell scripts as if they were functions... That is, taking an input value or string into the script. How do I approach doing this?

  • The shell command and any arguments to that command appear as numbered shell variables: $0 has the string value of the command itself, something like script, ./script, /home/user/bin/script or whatever. Any arguments appear as "$1", "$2", "$3" and so on. The count of arguments is in the shell variable "$#".

    Common ways of dealing with this involve shell commands getopts and shift. getopts is a lot like the C getopt() library function. shift moves the value of $2 to $1, $3 to $2, and so on; $# gets decremented. Code ends up looking at the value of "$1", doing things using a caseesac to decide on an action, and then doing a shift to move $1 to the next argument. It only ever has to examine $1, and maybe $#.

    the C `getopt()` is an extremely established standard, but the `getopt` executable is not the same across distro/platform. I'm a now fully converted `getopts` user, as it is a POSIX standard. It works great with `dash` also, which is my preferred script shell

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM