Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
I've gotten into Bash scripting and wrote a few scripts.
The only thing I can't seem to grasp is passing command line arguments to the script, like ./scriptname.sh -rif someone could point me to a good doc on this I'd appreciate it. I read the Advanced Scripting Guide and a lot of the small bash programming howto both on tldp.org, both touch on it very lightly.

In the simplest sense, getting the args is very easy. In your code, you use the variables $0, $1, $2 ...
$0 is always the script name and $1, $2 ... are the first, second, etc space separated arguments. I usually copy them into meaningful named variables:
> MyCleanupScript /data/logs .log
DirName=$1
Extension=$2
There is also a 'shift' command that you can use in the shell script so that you can process the args with a loop:ArgCount=$#
CurrentArg=$1
shiftwhile [ $ArgCount -ge 0 ]
do...
CurrentArg=$1
decrement CurrentArg count - I don't remember the syntax
shiftdone
The disadvantage of the above two methods is that the args have to be in the order expected by the code.To get around that, you use the shell script command 'getopts'. With 'getopts' you can define that you expect a -r arg with one option and -s with no options, and the arguments don't have to be in a specified order, so the same code can handle:
MyScript -d /data/logs -e .logs
and
MyScript -e.logs -d /data/logs
You can read about getopts in 'man bash' or maybe you can find more by doing a google search.

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |